Open XML格式化Excel数值
Open xml?中格式化Excel?中的數值時,需要使用NumberingFormat類,當Excel序列化成xml的時候,Numberingformat對象會被序列化成x:NumFmt。
?
NumFormat元素用于指定數值型數據是怎么格式化和呈現出來的。等同于在Excel上選中單元格后選擇數值格式,如下圖
?
指定一個單元格的數值格式有以下幾個步驟:
1.?創建一個數值格式的NumberingFormat,并設置一個Id(自定義),指定FormatCode,FormatCode可以是自定義的Code,也可以是一些系統約定的格如:"@"標示文本格式
NumberingFormat numberingFormat1 = new NumberingFormat() { NumberFormatId = id, FormatCode = formatStr };// "#0.00######"
??????????? formats.Append(numberingFormat1);
注:系統約定的格式有下面這些:
?
ID
formatCode
0
General
1
0
2
0.00
3
#,##0
4
#,##0.00
9
0%
10
0.00%
11
0.00E+00
12
# ?/?
13
# ??/??
14
mm-dd-yy
15
d-mmm-yy
16
d-mmm
17
mmm-yy
18
h:mm AM/PM
19
h:mm:ss AM/PM
20
h:mm
21
h:mm:ss
22
m/d/yy h:mm
37
#,##0 ;(#,##0)
38
#,##0 ;[Red](#,##0)
39
#,##0.00;(#,##0.00)
40
#,##0.00;[Red](#,##0.00)
45
mm:ss
46
[h]:mm:ss
47
mmss.0
48
##0.0E+0
49
@
把它添加到styleSheet的NumberingFormats中,
用這個numberFormatId創建CellFormat,添加到stylesheet的Cellformats中,返回Index
public static UInt32Value CreateCellFormat(Stylesheet styleSheet,UInt32Value fontIndex,UInt32Value fillIndex,UInt32Value numberFormatId){CellFormat cellFormat = null;int i = 0;if (cellFormat == null){cellFormat = new CellFormat();//isNew = true; }if (fontIndex != null)cellFormat.FontId = fontIndex;if (fillIndex != null)cellFormat.FillId = fillIndex;if (numberFormatId != null){cellFormat.NumberFormatId = numberFormatId;cellFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);}//if (isNew) styleSheet.CellFormats.Append(cellFormat);UInt32Value result = styleSheet.CellFormats.Count;styleSheet.CellFormats.Count++;return result;}?
?
最后指定單元格的StyleIndex為上面創建的NumberingFormat在
cell.StyleIndex = _textNumberStyleId;
?
OK.
?
示例代碼下載地址:
http://files.cnblogs.com/files/Hcsdn/ExcelDataImporter.rar
?
示例代碼調用方法如下:
?System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("server=.;database=demojc;user id=sa;password=!3323");
??????????? System.Data.SqlClient.SqlDataAdapter com = new System.Data.SqlClient.SqlDataAdapter("SELECT U.U_UserID,U.U_FirstName,Cast(u.U_F_ID as nvarchar(10)) FROM U", conn);
??????????? System.Data.DataSet ds = new DataSet();
??????????? com.Fill(ds);
??????????? ManuOnline.OpenXmlAnalysisReports.DataImporter.ImportData(@"E:\1.xlsx", "Sheet1", ds.Tables[0], null);
轉載于:https://www.cnblogs.com/Hcsdn/p/6912354.html
總結
以上是生活随笔為你收集整理的Open XML格式化Excel数值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Promise的几个扩展API总结
- 下一篇: 拥抱变化——从Atlas到ASP.NET