如何使用格式将Excel工作表复制到电子邮件正文?
问题描述:
我在服务器上创建一个控制台应用程序,该应用程序会将MS Excel文件(包含颜色和格式)的内容复制到电子邮件的正文中。我不是试图附上工作表,而只是复制它,以便业务用户在他们的手机/平板电脑/设备上查看电子邮件时,他们不需要安装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 protected]", "[email protected]");
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");
}
答
不是你正在寻找确切的答案,但如果你可以用PDF附件活那么我以前使用过类似的东西来将活动工作表导出为包含格式的PDF文件:
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
+0
这当然是Excel文件中的原始VBA。我相信有人对c#有更多的经验可以帮助你如何将它转化为你的服务器应用程序,或者你可以将VBA代码存储在你的excel文件中并从控制台代码中调用子代码。 –
+0
感谢您的输入! :-) –
是否需要位于正文中?它可能更多_user friendly_作为附件? – christiandev
您可以在HTML表格中显示数据以获得类似于Excel的格式。 – markpsmith
是Christiandev它必须位于主体中,以便业务用户在移动设备上查看报告时,不需要安装Excel。 –