Thecor
Thecor

Reputation: 88

OpenXML Spreadsheet corrupted in Excel

I am working with OpenXML (2.5) to create a customized spreadsheet. On the VM I am using, I only have Open Office in which the OpenXML spreadsheet was working fine (with custom formatting and everything). However, when moving the file to a machine with Microsoft Office, each version of the file failed to open due to corrupted data. I took out all the customization and still had a corrupted result (which still worked in Open Office).

This is the code I have for a bare bones spreadsheet file, which, again, works in Open Office but is seen as corrupt in Excel.

public string CreateGrid()
{
    var path = Path.GetTempFileName();
    var document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
    var workbookpart = document.AddWorkbookPart();

    workbookpart.Workbook.Save();
    document.Close();
    return path;
}

The error I get is 'An invalid character was found in the text content.' Line: 1 Column: 1 File Offset: 0 As you can see in the code, I'm not adding any text as of yet, it I'm fairly certain it isn't illegal characters. Any help would be greatly appreciated.

Upvotes: 2

Views: 6204

Answers (1)

Thecor
Thecor

Reputation: 88

I was able to figure out the problem. Firstly, with the code I have above, Excel expects a fully formatted file when using OpenXML. That means just having a file with a workbook won't suffice, it has to have the workbook, worksheets and at least 1 sheet for it to open properly. The other problem I had (where the data would not display in Excel), was because as I was traversing down rows, I was not creating a new row each time. For anyone attempting the same thing I was, the code should look like this:

foreach (var temp in tempList)
{
    if (cellIdex == 12)
    {
        cellIdex = 0;
        rowIdex = rowIdex + 1;
        row = new Row { RowIndex = rowIdex };
        sheetData.AppendChild(row);
     }
     cell = CreateTextCell(ColumnLetter(cellIdex), rowIdex, tempToString(), 3);
     row.AppendChild(cell);
     cellIdex = cellIdex + 1;
}  

The most important part to note is the "row = new Row{RowIndex = rowIdex};". Might seem simple but caused me a lot of headache.

Upvotes: 2

Related Questions