Search code examples
c#openxmlopenxml-sdk

Applying % number format to a cell value using OpenXML


I want to apply the % (percentage) number format using open XML C#

I have numeric value 3.6 that I want to display that number in excel as `3.6%.

How do I achieve that?


Solution

  •   WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
    

    Create a stylesheet,

     sp.Stylesheet = new Stylesheet();
    

    Create a numberingformat,

    sp.Stylesheet.NumberingFormats = new NumberingFormats();
    // #.##% is also Excel style index 1
                   
    

    NumberingFormat nf2decimal = new NumberingFormat();
    nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);
    nf2decimal.FormatCode = StringValue.FromString("0.0%");
    sp.Stylesheet.NumberingFormats.Append(nf2decimal);
    

    Create a cell format and apply the numbering format id

    CellFormat cellFormat = new CellFormat();
    cellFormat.FontId = 0;
    cellFormat.FillId = 0;
    cellFormat.BorderId = 0;
    cellFormat.FormatId = 0;
    cellFormat.NumberFormatId = nf2decimal.NumberFormatId;
    cellFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);
    cellFormat.ApplyFont = true;
    
    //append cell format for cells of header row
    sp.Stylesheet.CellFormats.AppendChild<CellFormat>(cellFormat);
    
    
    //update font count 
    sp.Stylesheet.CellFormats.Count = UInt32Value.FromUInt32((uint)sp.Stylesheet.CellFormats.ChildElements.Count);
                        
    
    //save the changes to the style sheet part   
    sp.Stylesheet.Save();
    

    and when you append the value to the cell have the following center code hereonversion and apply the style index in my case i had three style index hence the 3 one was my percentage style index i.e 2 since the indexes start from 0

    string val = Convert.ToString(Convert.ToDecimal(value)/100);
    Cell cell = new Cell();
    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
    cell.CellValue = new CellValue(val);
    cell.StyleIndex = 2;
    row.Append(cell);