从数据表中以c#格式发送带有excel作为附件的电子邮件

时间:2018-12-04 05:37:01

标签: c# excel email datatable console-application

我有一个数据表。我想将数据表的内容作为excel发送,并将电子邮件作为附件发送。我尝试了下面的代码,但它正在发送expty excel文件。

首先,我将数据表转换为流对象,并将流与其他邮件参数一起传递给sendemail方法。

 private static Stream DataTableToStream(System.Data.DataTable table)
        {
            const string semiColon = ";";

            var ms = new MemoryStream();
            var sw = new StreamWriter(ms);

            foreach (DataColumn column in table.Columns)
            {
                sw.Write(column.ColumnName);
                sw.Write(semiColon);
            }
            sw.Write(Environment.NewLine);
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
                    sw.Write(semiColon);
                }
                sw.Write(Environment.NewLine);
            }
            return ms;
        }

下面是sendmail代码

 private const string ExcelContentType = "application/ms-excel";

        private static bool SendMail(MailAddress from, string to, string[] CCAddress, String strSubject, String strBody, Attachment attachment, Stream tableStream)
        {
            try
            {
                const string attchmentName = "Weekly Vendor Report.xlsx";
                SmtpClient client = new SmtpClient();
                client.Host = "mail.lamrc.com";

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = from;
                message.IsBodyHtml = true;
                message.Subject = strSubject;
                message.Body = strBody;
                message.To.Add(to);

                message.Attachments.Add(new Attachment(tableStream, attchmentName, ExcelContentType));
.......

}

1 个答案:

答案 0 :(得分:1)

使用EPPlus库将数据表转换为excel并将其转换为附件。

    public static Attachment GetAttachment(DataTable dataTable)
    {
        MemoryStream outputStream = new MemoryStream();
        using (ExcelPackage package = new ExcelPackage(outputStream))
        {
            ExcelWorksheet facilityWorksheet = package.Workbook.Worksheets.Add("sheetName");
            facilityWorksheet.Cells.LoadFromDataTable(dataTable, true);

            package.Save();
        }

        outputStream.Position = 0;
        Attachment attachment = new Attachment(outputStream, "sample.xlsx", "application/vnd.ms-excel");

        retutn attachment;
    }