Search code examples
openxmlopenxml-sdk

Corrupt records from OpenXML Spreadsheet creation


I'm trying to generate a simple XLSX file using OpenXML but I'm getting an error when I open my file and the only info in the repairedRecord part of the log file is this:

Repaired Records: Cell information from /xl/worksheets/sheet1.xml part

The strange thing is that all the cells I'm trying to write do have the value I expect them to have. I'm just trying to write a single header row right now, where the headers is just an IEnumerable<string>:

using (var doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)) {
    var workbookPart = doc.AddWorkbookPart();
    workbookPart.Workbook = new Workbook();

    var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet();

    var sheets = workbookPart.Workbook.AppendChild(new Sheets());
    var sheet = new Sheet {
        Id = workbookPart.GetIdOfPart(worksheetPart),
        SheetId = 1,
        Name = "Sheet 1"
    };
    sheets.Append(sheet);

    workbookPart.Workbook.Save();

    var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

    var row = new Row { RowIndex = 1 };

    var column = 1;
    foreach (var header in headers)
        row.AppendChild(new Cell {
            CellReference = GetColumnLetter(column++) + "1",
            DataType = CellValues.SharedString,
            CellValue = new CellValue(header)
        });

    sheetData.Append(row);

    workbookPart.Workbook.Save();
}

Solution

  • If you're inserting a string value, you should be using CellValues.InlineString

      foreach (var header in headers)
            row.AppendChild(new Cell (new InlineString(new Text(header))) {
                CellReference = GetColumnLetter(column++) + "1",
                DataType = CellValues.InlineString
            });