使用 OpenXML 读取现有文件并附加一些数据行,然后 return 以字节形式下载表格

Using OpenXML read the existing file and append some rows with data, then return it as bytes so as to download the form

public static byte[] AddDataToPredifinedFormat(string path, string sheetName = "")
{
    byte[] fileBytes = null;
    var employee = new List<Employee>
                {
                    new Employee{Name = "XYZ", Number = "12345"},
                    new Employee{Name = "ABC", Number = "12345"}
                };
    try
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(ms, false))
            {
                WorkbookPart wbPart = document.WorkbookPart;
                IEnumerable<Sheet> sheets = wbPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                string sheetId = sheetName != "" ? sheets.Where(q => q.Name == sheetName).First().Id.Value : sheets.First().Id.Value;
                WorksheetPart wsPart = (WorksheetPart)wbPart.GetPartById(sheetId);
                SheetData sheetData = wsPart.Worksheet.GetFirstChild<SheetData>();
                foreach (var x in employee)
                {
                    Row newRow = new Row();
                    Cell cell = new Cell();
                    cell.CellValue = new CellValue(x.Name.ToString());
                    cell.StyleIndex = 0;
                    newRow.AppendChild(cell);
                    sheetData.AppendChild(newRow);
                }
                wbPart.Workbook.Save(ms);
                fileBytes = ms.ToArray();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return fileBytes;
}

正在读取现有文件并附加行,但在下载文件时,Excel 应用程序显示它已损坏。 使用 OpenXML 读取现有文件并附加一些数据行,然后 return 以字节形式下载表格

你能试试把 fileBytes = ms.ToArray(); 移到内部 using 块的外面吗?

我有与此非常相似的代码,用于使用 OpenXML 修改 WordprocessingDocuments,但我不使用 MemoryStream。我File.Copy原来的到一个临时文件,修改,保存然后从临时文件加载byte[]进行流式传输。

我认为为了 return sheet 你需要稍微重构一下代码。与其期望内存流直接写入数组并下载文件无济于事, 我所做的是在我的代码中:

  • 将数据写入流并读回。所以你需要return更新的流
  • 将流数据写入ExcelPackage

像这样

using OfficeOpenXml;

Stream stream = new MemoryStream(<process and return your steam>);
  using (ExcelPackage package = new ExcelPackage(stream))
            {
                //write any more extra data to sheet
                return package.GetAsByteArray();
            }

需要注意的重要一点是:package.GetAsByteArray();