gpt4 book ai didi

c# - openXML电子表格文档返回用于MVC文件下载的字节数组

转载 作者:行者123 更新时间:2023-12-02 03:02:12 25 4
gpt4 key购买 nike

我试图以 byte[] 的形式返回一个 openXML 电子表格文档,然后我可以使用它来允许我的 MVC 将该文件发送给用户。这是我的电子表格文档方法,用于返回字节数组

using (MemoryStream mem = new MemoryStream())
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(mem, SpreadsheetDocumentType.Workbook);

// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();

// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());

// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());

SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

//row start
for (int id = 0; id <= reports.Count(); id++)
{
if (id == 0)
{
Row contentRow = CreateContentRow(reports.ElementAt(id), true, 2 + id);
sheetData.AppendChild(contentRow);
}
else
{
Row contentRow = CreateContentRow(reports.ElementAt((id - 1)), false, 2 + id);
sheetData.AppendChild(contentRow);
}
}

// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
workbookpart.Workbook.Save();
return mem.ToArray();
}

然后在我的 MVC Controller 中我这样调用它

return File(crs.CreateReportSpreadSheet(reports),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Reports.xlsx");

文件已下载,但当您打开时,它会显示一条错误消息,表明文件已损坏。有没有其他方法可以让他们下载这个文件?

最佳答案

我知道这已经晚了,但我相信这是因为您在完成电子表格文档后没有关闭它。确保在返回内存流以提交文档使用的所有底层流之前关闭文档。

// code omitted for clarity...
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return mem.ToArray()

http://msdn.microsoft.com/en-gb/library/documentformat.openxml.packaging.spreadsheetdocument(v=office.14).aspx

关于c# - openXML电子表格文档返回用于MVC文件下载的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com