Home » excel » OpenXML Spreadsheet: Excel gives an error, then mends it and it works. (C#)

OpenXML Spreadsheet: Excel gives an error, then mends it and it works. (C#)

Posted by: admin March 9, 2020 Leave a comment

Questions:

I narrowed it down to:

       //aantal auto's
        Row aantalAutosRow = new Row();
        aantalAutosRow.RowIndex = Convert.ToUInt32((tblXML.Rows.Count) + 2);

        Cell aantalAutosCell = new Cell();
        aantalAutosCell.CellReference = getColumnName(1);
        aantalAutosCell.CellValue = new CellValue("Hoi");

        aantalAutosRow.Append(aantalAutosCell);
        sheetData.Append(aantalAutosRow);

This generates the Cell after I click yes when Excel prompts to fix the file (sheet.xml)

Complete class:

Can someone tell me what I’m doing that is illegal to Excel? I think excel makes SharedStrings when mending it. I never worked with SharedStrings and I hope I don’t have to.

How to&Answers:

I went through your code and found 4 places that needed change in order to generate a fault-free excel document.

  • 1. Replaced stylesPart.Stylesheet = s.GenerateStyleSheet();
    by stylesPart.Stylesheet = new Stylesheet();
  • 2. Commented out the following : //headerCell.StyleIndex = 1;
  • 3. Commented out the following : //StyleIndex = 6,
  • 4. Added the following : aantalAutosCell.DataType = CellValues.String;
  • The code posted below works for me and generates an error free excel document.
    Few pointers you need to know

  • 1. You cannot arbitrarily assign style indices when working with Open XML Docs
  • 2. When ever you have a string data type to be stored you should use CellValues.String (since you don’t want to use Shared String)
  • 3. It’s really worth while to read about SharedStrings when working with Open XML SDK. Shared Strings reduce the overall size of your file and make things so much better. See http://msdn.microsoft.com/en-us/library/office/gg278314.aspx