能不能使用powershell写一个获取excel内容并通过邮件发送出去的脚本
可以,以下是一个示例脚本:
# 设置Excel文件路径和邮件信息
$excelFilePath = "C:\path\to\your\excel\file.xlsx"
$smtpServer = "smtp.example.com"
$fromAddress = "sender@example.com"
$toAddress = "recipient@example.com"
$subject = "Excel内容"
# 创建Excel.Application对象
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# 打开Excel文件
$workbook = $excel.Workbooks.Open($excelFilePath)
$worksheet = $workbook.Sheets.Item(1)
# 获取Excel数据
$numRows = ($worksheet.UsedRange.Rows).Count
$numColumns = ($worksheet.UsedRange.Columns).Count
$data = @()
for ($i = 1; $i -le $numRows; $i++) {
$row = @()
for ($j = 1; $j -le $numColumns; $j++) {
$cellValue = $worksheet.Cells.Item($i, $j).Value2
$row += $cellValue
}
$data += $row
}
# 关闭Excel文件和对象
$workbook.Close($false)
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
# 构建邮件内容
$body = "Excel内容:`n`n"
foreach ($row in $data) {
$rowString = ""
foreach ($cell in $row) {
$rowString += "$cell`t"
}
$body += "$rowString`n"
}
# 发送邮件
$mailMessage = New-Object System.Net.Mail.MailMessage($fromAddress, $toAddress, $subject, $body)
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer)
$smtpClient.Send($mailMessage)
要运行此脚本,您需要将Excel文件路径、SMTP服务器和邮件地址替换为实际值,然后将脚本保存为.ps1文件并在PowerShell中运行。请注意,此脚本需要安装Microsoft Excel才能正常工作
原文地址: http://www.cveoy.top/t/topic/g1KD 著作权归作者所有。请勿转载和采集!