问题
I made a routine to export a data table to excel. However, when I open the generated file in Excel 2013, I obtain an error saying
Repaired Records: "Informations of cell in part /xl/worksheets/sheet1.xml"
even though, when I click OK the document opens apparently well. The data appears to be ok.
The code of the controller is:
public IActionResult ExportingXl()
{
OrdListViewModel o = HttpContext.Session.GetJson<OrdListViewModel>("MyVar");
ExportExcelModel x = new ExportExcelClass(o.oTable); // this creates the excel file contents
return File(x.ExcelContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "mydoc.xlsx");
}
The ExportExcelClass is:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class ExportExcelClass
{
public byte[] ExcelContent;
public ExportExcelModel(List<OrdViewModel> ol)
{
MemoryStream memstream = new MemoryStream();
SpreadsheetDocument XlsxDoc = SpreadsheetDocument.Create(memstream, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = XlsxDoc.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 = XlsxDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = XlsxDoc.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Folha1"
};
sheets.Append(sheet);
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
// filling the header row
Row row = new Row();
Cell cell;
cell = new Cell()
{
CellReference = ExcelReference(0, 0),
DataType = CellValues.String,
CellValue = new CellValue("Nb.")
};
row.Append(cell);
// etc. for the other cells in the row
sheetData.Append(row);
// filling the body of the excel file
int rowidx = 1;
foreach (OrdViewModel ovm in ol)
{
row = new Row();
cell = new Cell()
{
CellReference = ExcelReference(rowidx,0),
DataType = CellValues.Number,
CellValue = new CellValue(ovm.eID.ToString())
};
row.Append(cell);
// fills the rest of the row ...
row.Append(cell);
sheetData.Append(row);
rowidx++;
}
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
// Close the document.
XlsxDoc.Close();
ExcelContent = memstream.ToArray();
}
private string ExcelReference(int row, int col) // only for rows between A-Z
=> ((char) (col + 65)).ToString() + (row + 1).ToString();
}
来源:https://stackoverflow.com/questions/59825738/exporting-data-to-excel-format-error-when-opening-resulting-file