5

我有一个使用 OpenXML 2 构建的 Excel 文件,我想将其作为电子邮件附件发送。例如

    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
    AddParts(package); //created using document reflector

使用将电子表格保存到临时文件

stream.WriteTo(new System.IO.FileStream(@"c:\test.xlsx", System.IO.FileMode.Create));

工作正常。但是尝试将流直接作为电子邮件附件发送失败 - 当我这样做时,只需将一个空文件附加到电子邮件中

System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel");

有人知道怎么做吗?

4

4 回答 4

5

好的,我得到了这个工作,虽然通过一些努力。要创建流:

MemoryStream stream = new MemoryStream();

using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
  Excel.CreateSpreadsheet(package, Excel_Methods.CreateSpotQuoteOut(), true);
}

stream.Seek(0, SeekOrigin.Begin);

System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(stream, "spreadsheet.xlsx");

attach.ContentDisposition.CreationDate = DateTime.Now;
attach.ContentDisposition.ModificationDate = DateTime.Now;
attach.ContentDisposition.Inline = false;
attach.ContentDisposition.Size = stream.Length;
attach.ContentType.MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 

另外,我发现创建它们后我的并没有立即发送,原因是“standalone = yes”没有被添加到所有页面的 xml 声明中,所以在我的 AddParts 函数中,在添加部件之后,我将它们传递给这个函数:

private static void AddXMLStandalone(OpenXmlPart part)
        {
            System.IO.StreamWriter writer = new System.IO.StreamWriter(part.GetStream());

            XmlDocument doc = new XmlDocument();
            doc.Load(part.GetStream());

            doc.InnerXml = doc.InnerXml.Substring(doc.InnerXml.IndexOf("?>") + 2);
            doc.InnerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + doc.InnerXml;

            part.GetStream().SetLength(doc.InnerXml.Length);
            doc.Save(writer);
            writer.Flush();
            writer.Close();            
        }

祝你好运!

于 2010-04-05T18:20:00.220 回答
2

做这个:

System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(new MemoryStream(stream.ToArray()), "MobileBill.xlsx", "application/vnd.ms-excel");

显然内存流没有被刷新或其他东西

于 2011-11-18T14:18:29.130 回答
1

对于您的“内容不可读”问题,请确保 Save() 您的工作簿和工作表并将您的电子表格文档包含在 using 语句中,以确保所有包和压缩流都被刷新、关闭等。

System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)))
{
    AddParts(package); 
    //Save if AddParts hasn't done it
}
System.Net.Mail.Attachment file =  ...
于 2009-07-03T06:21:52.843 回答
0

考虑负载:附件类是否期望从提供的流中的当前位置读取?如果是这种情况,您可能必须“寻找”回到流的开头,然后再将其提供给 Attachment 构造函数:

AddParts(package); //created using document reflector
stream.Seek(0, SeekOrigin.Begin);
System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel");
于 2009-06-25T13:58:32.413 回答