使用SpreadsheetGear将电子表格作为电子邮件附件发送

时间:2012-11-19 11:17:29

标签: .net email-attachments memorystream system.net.mail spreadsheetgear

客户已要求我增强其中一个应用,以便发送包含Excel电子表格的电子邮件。他们碰巧有一个旧版的SpreadsheetGear(2009),所以我认为如果我使用它可能会节省时间。

实际上,SpreadsheetGear非常适合实际创建电子表格,但我无法将其作为电子邮件附件发送。只是想知道是否有人这样做过?理论上它应该很简单,我目前的代码如下:

    /// <summary>
    /// Creates an email attachment based upon the inbound workbook
    /// </summary>
    /// <param name="workbook">The workbook</param>
    /// <returns>an email Attachment</returns>
    private static Attachment CreateAttachment(string id, IWorkbook workbook)
    {
        // Open up a memorystream and save out to it
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        workbook.SaveToStream(memoryStream, SpreadsheetGear.FileFormat.OpenXMLWorkbook);

        return new Attachment(memoryStream, id + ".xls", "application/vnd.ms-excel");
    }

其中workbook是一个完全填充的SpreadsheetGear工作簿。在此之后,使用

将Attachment对象推送到System.Net.Mail.MailMessage对象
MailMessage.Attachments.Add(attachment);

我所看到的是:

  • 电子邮件已发送正常,并附有正确名称的附件
  • 但是附件是空的

在开发环境中,我在那里放了一些调试代码

workbook.SaveAs("c:\\test.xls", SpreadsheetGear.FileFormat.OpenXMLWorkbook);

产生了所需的电子表格,作为文件。但很明显,因为我最终只是通过电子方式发送,所以如果可以的话,我会尽快避免写入磁盘。关于我出错的地方的任何指示?

谢谢, 皮特

(应该最后添加升级到最新的SpreadsheetGear不是一个选项,无论是这种方法还是手动执行!环境是VS2008,.net 3.5)

3 个答案:

答案 0 :(得分:2)

我尝试使用你问题中的代码。它对我有用,经过两次小修改。

1)由于您保存为OpenXMLWorkbook格式,我将扩展名更改为.xlsx而不是.xls。

2)保存workbook.SaveToStream方法后,我添加了以下代码行。

memoryStream.Seek(0, System.IO.SeekOrigin.Begin);

这会将位置设置为流的开头。当我尝试使用没有它的代码时,我在尝试打开Excel附件时收到错误。

如果没有这些修改,我会收到错误,但我从未得到过空的附件。我使用的是最新版本的SSG,但我不明白为什么在这种情况下这应该是重要的。

答案 1 :(得分:0)

STEP.1

DownLoad ClosedXML dll并添加对项目的引用

步骤2。下载DocumentFormat.OpenXML并添加引用  项目

使用System.IO;

使用ClosedXML.Excel;

public void send mail(){

DataTable dt = smp.GetDataTable(&#34;选择l.EMPID为[EmpID],e.Emp_Name为[EmpName],l.LDate为[ApplicationDate],l.StartDate为[FromDate],l.EndDate作为[ToDate]来自LeaveTable&#34;);

XLWorkbook wb = new XLWorkbook();

var ws = wb.Worksheets.Add(dt,sheetName);

System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();    wb.SaveAs(MemoryStream的);

memoryStream.Seek(0,System.IO.SeekOrigin.Begin);

System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(memoryStream,sheetName +&#34; .xlsx&#34;,&#34; application / vnd.ms-excel&#34;) ;

SendEmail(To,To1,Subject,Body,attachment);

}

public static bool SendEmail(string pTo,string pTo1,string pSubject,string pBody,System.Net.Mail.Attachment attachment)         {

            MailMessage myMail = new MailMessage();

         ConfigurationSettings.AppSettings["emailid"].ToString();


            SmtpSection settings =(SmtpSection) ConfigurationManager.GetSection("system.net/mailSettings/smtp");
            var email = settings.Network.UserName;

            bool ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["ssl"].ToString());

            myMail.From = new MailAddress(email);
            myMail.To.Add(pTo);
            if (pTo1 != "")
            {
                myMail.CC.Add(pTo1);
            }
            myMail.Subject = pSubject;
            myMail.Body = pBody;
            myMail.Priority = MailPriority.High;
            myMail.Attachments.Add(attachment);


            SmtpClient client = new SmtpClient();
            client.EnableSsl = ssl;


            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.Send(myMail);
            LogMessage.LogMsg = "Mailsent to:" + pTo + myMail.Body;
            LogMessage.CreateLogFile();

            return true;

        }

答案 2 :(得分:0)

    private void GenerateFile(List<TrickleFieldInfo> info)
            {
                MemoryStream memoryStream = new MemoryStream();
                try
                {
                    var workBook = new XLWorkbook();
                    var workSheet = workBook.Worksheets.Add("trickle_field");

                    workSheet.Cell(1, 1).Value = "Debit";
                    workSheet.Cell(1, 2).Value = "Credit";
                    workSheet.Cell(1, 3).Value = "Balance";
                    workSheet.Range(1, 1, 1, 3).AddToNamed("heading");
                    workSheet.Cell(2, 1).InsertData(info.AsEnumerable());

                    var titlesStyle = workBook.Style;
                    titlesStyle.Font.Bold = true;
                    titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    titlesStyle.Fill.BackgroundColor = XLColor.Cyan;

                    workBook.NamedRanges.NamedRange("heading").Ranges.Style = titlesStyle;

                    workSheet.Columns().AdjustToContents();
                    workBook.SaveAs(memoryStream);

                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);

                    EmailToBackOffice(ref memoryStream);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    memoryStream.Dispose();
                    memoryStream.Close();
                }
            }

public void EmailToBackOffice(ref MemoryStream memoryStream)
        {    
            SmtpClient client = new SmtpClient();
            MailMessage msg = new MailMessage();
            msg.Body = "";
            msg.IsBodyHtml = true;
            msg.Subject = "<Email subject here>";
            msg.Priority = MailPriority.Normal;
            msg.Sender = new MailAddress(<From address here>);
            msg.From = new MailAddress(<From address here>);
            msg.To.Add(new MailAddress(<To address here>));

            var attachment = new System.Net.Mail.Attachment(memoryStream, "trickle_field.xlsx", "application/vnd.ms-excel");
            msg.Attachments.Add(attachment);

            client.Host = "Host name here";
            client.Credentials = new System.Net.NetworkCredential("username", "password");
            client.Send(msg);
        }