Failed to apply number format with OpenXML in C #

I am trying to get a column in an excel document I am creating using OpenXML, which needs to be formatted in a friendly way for 12-bit UPC.

For this I am using the following code (based on this question ):

var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet {NumberingFormats = new NumberingFormats(), CellFormats = new CellFormats()};

var upcFormatting = new NumberingFormat {NumberFormatId = 164, FormatCode = "000000000000"};

var upcCellFormat = new CellFormat
                                        NumberFormatId = upcFormatting.NumberFormatId,
                                        FontId = 0U,
                                        FillId = 0U,
                                        BorderId = 0U,
                                        FormatId = 0U,
                                        ApplyNumberFormat = BooleanValue.FromBoolean(true)


var styleIndex = sp.Stylesheet.CellFormats.Count;



The above code unfortunately creates a stylesheet that appears to be considered corrupted, looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<x:styleSheet xmlns:x="">
   <x:numFmts count="1">
     <x:numFmt formatCode="000000000000" numFmtId="164"/>
   <x:cellXfs count="1">
   <x:xf numFmtId="164" applyNumberFormat="1" xfId="0" borderId="0" fillId="0" fontId="0"/> 


If anyone could please explain how I can get a valid stylesheet generated with a numbering format that allows 12 digits to be displayed using OpenXML only (you can't use any frameworks built around it like ClosedXML) I was would be very grateful.



source to share

1 answer

There is no default style in the style sheet. Add the following line (it should be the first one) and change the cellXfs counter to 2. Remember to update your sheet to use the style "2" instead of "1".

<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>




All Articles