4

我正在使用 NPOI 创建一个 Excel 工作簿并尝试将其作为电子邮件附件发送。我的代码如下:

var wb = new HSSFWorkbook();

//create the workbook

using(var ms = new MemoryStream())
{
    wb.Write(ms);
    var msg = new MailMessage();

    //create email

    msg.Attachments.Add(new Attachment(ms, "Document.xls", "application/vnd.ms-excel"));

    client.Send(msg);
}

我已经排除了创建工作簿的代码,我已经测试以确保它可以正常工作(我能够保存文件并毫无问题地打开它)但是如果您想查看任何内容,请询问。client只是我的SmtpClient

电子邮件发送没有问题,附件显示为 Document.xls(如预期的那样),但是当我打开它时,我收到以下消息(在 Excel 2010 中),当我单击“是”打开时,工作表是空白的。

The file you are trying to open, 'Document.xls', is in a differrent format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

据我所知,我正在指定格式。有谁看到我做错了什么?任何帮助,将不胜感激。

4

1 回答 1

8

我终于弄明白了。在将 传入 之前StreamAttachment我需要将其位置设置回零。

ms.Position = 0;

而已!

于 2013-12-12T19:21:26.643 回答