我正在服务器上创建一个控制台应用程序,它将MS Excel文件的内容(带有颜色和格式)复制到电子邮件正文中。我不是要附加工作表,而只是复制它,以便当业务用户在手机/平板电脑/设备上查看电子邮件时,他们不需要安装Excel应用程序来查看报告。
我需要帮助来弄清楚如何在电子邮件正文中复制和显示工作表。
目前我有以下内容,但它只复制实际的字符串数据,而不是任何漂亮的格式:
public static void pullDataFromExcel(string fileName)
{
string mySheetPath = @"C:\Users\lmilligan\Downloads\";
MSExcel.Application excelApp = new MSExcel.Application();
excelApp.DisplayAlerts = false;
excelApp.Visible = true;
MSExcel.Workbook book = excelApp.Workbooks.Open(mySheetPath + fileName);
MSExcel.Worksheet sheet = book.ActiveSheet;
book.RefreshAll();
var data = "";
foreach (MSExcel.Range row in sheet.UsedRange.Rows)
{
foreach (MSExcel.Range cell in row.Columns)
{
data += cell.Value + " ";
}
data += "\n";
}
MSOutlook.Application olApp = new MSOutlook.Application();
MailMessage mail = new MailMessage("email@myServer.com", "thisIsMe@myServer.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.myServer.net";
mail.Subject = "AutoMailer test";
mail.Body = Convert.ToString(sheet);
client.Send(mail);
book.Save();
book.Close();
excelApp.Quit();
}
static void Main(string[] args)
{
pullDataFromExcel("mySheet.xlsx");
}
答案 0 :(得分:0)
不是您正在寻找的确切答案,但如果您可以使用PDF附件,那么我之前使用类似于此的内容将活动工作表导出为PDF文件,包括格式:< / p>
Sub PDFMail()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String
Dim OutlApp As Object
' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & FName & ".pdf"
' Export activesheet as PDF
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)
' Prepare e-mail
.Subject = "SUBJECT HERE"
.To = "TO HERE"
.CC = "CC HERE
.BCC = "BCC HERE"
.Body = "BODY TEXT HERE"
.Attachments.Add PdfFile
' Try to send
On Error Resume Next
.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete PDF file
Kill PdfFile
' Quit Outlook if it was created by this code
If IsCreated Then OutlApp.Quit
' Release the memory of object variable
Set OutlApp = Nothing
End Sub