2016-05-23 31 views
2

我目前正在使用Open XML框架來導出Excel文件。我遇到的問題是,此電子表格的其中一列必須是十進制格式(#,###。##),它必須允許總和。我可以使用下面的方法以這種格式完美輸出Excel:如何在OpenXML中爲十進制格式(#,###。##)創建CellValue

private static Cell CreateTextCell(string header, UInt32 index, object text, CellStyleIndex cellStyle) 
{ 
    var cell = new Cell 
    { 
     DataType = CellValues.InlineString, 
     CellReference = header + index, 
     StyleIndex = (UInt32)cellStyle 
    }; 

    var istring = new InlineString(); 
    var t = new Text { Text = text.ToString() }; 
    istring.AppendChild(t); 
    cell.AppendChild(istring); 
    return cell; 
} 

正如你所看到的,我指定StyleIndex它適用我提到的格式。但這樣做的問題是,Excel可以識別此值作爲文本:

enter image description here

,這就是爲什麼我試圖創建它,一旦我想在文件中創建一個小數調用一個新方法:

private static Cell CreateValueCell(string header, UInt32 index, decimal value, CellStyleIndex cellStyle) 
{ 
    var cell = new Cell 
    { 
     DataType = CellValues.Number, 
     CellReference = header + index, 
     StyleIndex = (UInt32)cellStyle, 
     CellValue = new CellValue(value.ToString()) 
    }; 

    return cell; 
} 

通過這樣做,我達到怎樣的數字轉換,但我失去了小數位,你可以在下面的圖片中看到:

enter image description here

我看到一個名爲DecimalValue的類,但我無法弄清楚如何將它附加到單元格中。有關如何解決它的任何想法?

回答

4

您應該閱讀that article

主要概念是使用自定義CellFormatNumberingFormat

var nformat4Decimal = new NumberingFormat 
        { 
         NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++), 
         FormatCode = StringValue.FromString("#,##0.0000") 
        };