我正在使用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的形式存在(正如预期的那样),但是当我打开它时会收到以下消息(在Excel2010中),当我单击“是”打开工作表时,工作表是空的。
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?
据我所知,我正在指定格式。有人看到我做错什么了吗?任何帮助都将不胜感激。
发布于 2013-12-12 19:21:26
我终于想出来了。在将Stream传递到Attachment之前,我需要将它的位置设置为零。
ms.Position = 0;就这样!
https://stackoverflow.com/questions/20550710
复制相似问题