使用openXML 2.0保存excel文档时,文件已损坏,无法打开
本文关键字:已损坏 文件 openXML 保存 文档 excel 使用 | 更新日期: 2023-09-27 18:05:52
我试图保存行通过这个方法从另一个电子表格,并将此电子表格作为附件保存到电子邮件。邮件发送正常,但是附件没有打开,错误提示"文件损坏,无法打开"。我尝试将文件保存到c:上的filstream,但得到了相同的错误。这段代码有什么问题?
public static void CreateErrorMailWithExcelAttachment(List<Row> rows)
{
if (rows.Count > 0)
{
using (MemoryStream stream = new MemoryStream())
{
//Create a spreadsheet document by supplying the file name.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document.
spreadsheetDocument.AddWorkbookPart();
spreadsheetDocument.WorkbookPart.Workbook = new Workbook();
spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet();
// create sheet data
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(new SheetData());
// Add Rows to the Sheet.
foreach (Row row in rows)
{
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(new Row(row.OuterXml));
}
spreadsheetDocument.WorkbookPart.Workbook.Save();
}
Dictionary<string, byte[]> attachments = new Dictionary<string, byte[]>();
attachments.Add("Book1.xlsx", stream.ToArray());
SendEmail
(
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPServer"),
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPUser"),
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPPass"),
"shaun.bosch@acsis.co.za",
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "InstitutionalDatabaseAdminEmail"),
"Failed rows from bulk investor spreadsheet upload",
"Test",
false,
attachments
);
}
}
}
在WorkbookPart中,您需要添加一个元素,指定工作簿中的每个工作表。因为有很多未分配的创建者,所以很难准确地写出需要对代码进行的更改,但基本上需要:
workbook1.AddNamespaceDeclaration("r","http://schemas.openxmlformats.org/officeDocument/2006/relationships");
Sheets sheets1 = new Sheets();
Sheet sheet1 = new Sheet(){ Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "R71b609d3bfb541ee" };
sheets1.Append(sheet1);
workbook1.Append(sheets1);
workbookPart1.Workbook = workbook1;
你必须获得id标识符并把它放在那里,但是你应该可以很好地运行。
希望有帮助!