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