导出.Net时损坏的Excel/电子表格文件
从以下代码导出的电子表格文件似乎已损坏。我正在使用.Net核心API返回带有以下测试代码的文件。谁能告诉我我做错了什么?
提前感谢!
[Route("api/tools")]
public class ImportExportController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public ImportExportController(IHostingEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
[HttpGet]
[Route("export")]
public async Task<IActionResult> Export()
{
string sWebRootFolder = this._hostingEnvironment.WebRootPath;
string sFileName = @"demo.xls";
string URL = string.Format("{0}://{1}/{2}", this.Request.Scheme, this.Request.Host, sFileName);
FileInfo filePath = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
var memory = new MemoryStream();
SpreadsheetManager.SpreadsheetGenerator(filePath.FullName, sFileName);
using (var stream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return this.File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
}
}这是SpreadsheetManager的代码
public static class SpreadsheetManager
{
public static void SpreadsheetGenerator(string filePath, string fileName)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook);
using (document)
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Test Sheet" };
sheets.Append(sheet);
workbookPart.Workbook.Save();
}
}
}发布于 2018-02-02 00:56:12
交叉发布对问题的评论的答案:
OpenXML很容易出错,当你出错时,工具和办公软件都不会帮你。
为此,使用OpenXML创建文档的官方文档是创建所需的文件(在本例中使用Excel),然后使用OpenXML Productivity Tool打开该文件,并提取生成该文件的C#代码并使用该文件。
当您准备好继续阅读更复杂的OpenXML文档时,通过OpenXML documentation阅读它将是值得的。
https://stackoverflow.com/questions/48566834
复制相似问题