How to get cell value with applied formatting (formatted cell value) with OpenXML SDK

前端 未结 2 522
日久生厌
日久生厌 2020-12-15 07:42

I\'ve been googling and searching on the site for the answer, but I couldn\'t find a solution - everywhere people mostly discuss how to add new number format to the document

相关标签:
2条回答
  • 2020-12-15 07:54

    Men, this is a hard one... I will be adding here things that i found that could be worth..

    First is to get the numbering format of the cell (once you have the CellFormat:

    string format = excel.WorkbookPart.WorkbookStylesPart.Stylesheet.NumberingFormats.Elements<NumberingFormat>()
                .Where(i => i.NumberFormatId.ToString() == cellFormat.NumberFormatId.ToString())
                .First().FormatCode;
    

    For more information about this you can go to: NumberingFormats

    Im trying to find out how to apply this format to the cell.CellValue property... I think thats the way you have to go!

    Ok, reading the ClosedXml code (its open source), seems to be easy to get the format.

    Simply convert the value text to its type (int, double, etc) and call the ToString method passing the format. I was trying do that with the String.Format and didnt work. Ive tested the ToString and it works, but something still missing.

    I recommend to you to look at this class and get the code from the method GetFormattedString() as @El G tell in his comment.

    Bassicaly you will have to add something like this:

    double d = double.Parse(cell.CellValue.InnerText);
    string val = d.ToString(format);
    

    Hope it helps you...

    0 讨论(0)
  • 2020-12-15 08:10

    If you want to take cell value with applied formatting, same as displayed in Excel, use .Text property of Cell object. Like this:

    String formattedValue = cell.Text
    
    0 讨论(0)
提交回复
热议问题