什么是npoi ?

  简而言之,npoi就是可以在没有office的情况下对word或excel文档进行读写等操作。

使用方式 :

  1、准备npoi的dll文件

    下载链接:

  2、将下载的dll文件引入项目中

  3、引用命名空间

     

须知:

  1、excel表格分为:workbook(工作薄)-> sheet(工作表) -> 行:row 单元格:cell。

  2、npoi是poi的c#版本,npoi的行和列的index都是从0开始

  3、poi读取excel有两种格式一个是hssf,另一个是xssf。 hssf和xssf的区别如下: 
     hssf is the poi project’s pure java implementation of the excel ’97(-2007) file format. 
     xssf is the poi project’s pure java implementation of the excel 2007 ooxml (.xlsx) file format. 
     即:hssf适用2007以前的版本,xssf适用2007版本及其以上的。

       下面使用npoi读取excel例子:主要功能是将datatable导入excel,或将excel读取到datatable中。

代码如下:

 1       /// <summary>
 2         /// 将datatable导入到excel
 3         /// </summary>
 4         /// <param name="data">要导入的数据</param>
 5         /// <param name="filepath">导入的文件路径(包含文件名称)</param>
 6         /// <param name="sheename">要导入的表名</param>
 7         /// <param name="iscolumwrite">是否写入列名</param>
 8         /// <returns>导入excel的行数</returns>
 9         public int datatabletoexcel(datatable data, string filepath, string sheename, bool iscolumwrite)
10         {
11             int i = 0;
12             int j = 0;
13             int count = 0;
14             isheet sheet = null;
15             using (fs = new filestream(filepath, filemode.openorcreate, fileaccess.readwrite))
16             {
17                 //根据excel不同版本实例不同工作铺
18                 if (filepath.indexof(".xlsx") > 0) // 2007版本
19                 {
20                     workbook = new xssfworkbook();
21                 }
22                 else if (filepath.indexof(".xls") > 0) // 2003版本
23                     workbook = new hssfworkbook();
24 
25                 try
26                 {
27                     if (workbook != null)
28                     {
29                         sheet = workbook.createsheet(sheename);
30                     }
31                     else
32                     {
33                         return -1;
34                     }
35 
36                     if (iscolumwrite == true) //写入datatable的列名
37                     {
38                         irow row = sheet.createrow(0);
39                         for (j = 0; j < data.columns.count; ++j)
40                         {
41                             row.createcell(j).setcellvalue(data.columns[j].columnname);
42                         }
43                         count = 1;
44                     }
45                     else
46                     {
47                         count = 0;
48                     }
49 
50                     for (i = 0; i < data.rows.count; ++i)
51                     {
52                         irow row = sheet.createrow(count);
53                         for (j = 0; j < data.columns.count; ++j)
54                         {
55                             row.createcell(j).setcellvalue(data.rows[i][j].tostring());
56                         }
57                         count++;
58                     }
59                     workbook.write(fs); //写入到excel
60                     return count;
61                 }
62                 catch (exception ex)
63                 {
64                     console.writeline("exception: " + ex.message);
65                     return -1;
66                 }
67                 finally { fs.close(); fs.dispose(); }
68             }
69         }

 

 1       /// <summary>
 2         /// 将excel导入datatable
 3         /// </summary>
 4         /// <param name="filepath">导入的文件路径(包括文件名)</param>
 5         /// <param name="sheetname">工作表名称</param>
 6         /// <param name="isfirstrowcolumn">第一行是否是datatable的列名</param>
 7         /// <returns>datatable</returns>
 8         public datatable exceltodatatable(string filepath, string sheetname, bool isfirstrowcolumn)
 9         {
10             isheet sheet = null;//工作表
11             datatable data = new datatable();
12 
13             var startrow = 0;
14             using (fs = new filestream(filepath, filemode.open, fileaccess.read))
15             {
16                 try
17                 {
18                     if (filepath.indexof(".xlsx") > 0) // 2007版本
19                         workbook = new xssfworkbook(fs);
20                     else if (filepath.indexof(".xls") > 0) // 2003版本
21                         workbook = new hssfworkbook(fs);
22                     if (sheetname != null)
23                     {
24                         sheet = workbook.getsheet(sheetname);
25                         if (sheet == null) //如果没有找到指定的sheetname对应的sheet,则尝试获取第一个sheet
26                         {
27                             sheet = workbook.getsheetat(0);
28                         }
29                     }
30                     else
31                     {
32                         sheet = workbook.getsheetat(0);
33                     }
34                     if (sheet != null)
35                     {
36                         irow firstrow = sheet.getrow(0);
37                         int cellcount = firstrow.lastcellnum; //行最后一个cell的编号 即总的列数
38                         if (isfirstrowcolumn)
39                         {
40                             for (int i = firstrow.firstcellnum; i < cellcount; i++)
41                             {
42                                 icell cell = firstrow.getcell(i);
43                                 if (cell != null)
44                                 {
45                                     string cellvalue = cell.stringcellvalue;
46                                     if (cellvalue != null)
47                                     {
48                                         datacolumn column = new datacolumn(cellvalue);
49                                         data.columns.add(column);
50                                     }
51                                 }
52                             }
53                             startrow = sheet.firstrownum + 1;
54                         }
55                         else
56                         {
57                             startrow = sheet.firstrownum;
58                         }
59                         //读数据行
60                         int rowcount = sheet.lastrownum;
61                         for (int i = startrow; i < rowcount; i++)
62                         {
63                             irow row = sheet.getrow(i);
64                             if (row == null)
65                             {
66                                 continue; //没有数据的行默认是null
67                             }
68                             datarow datarow = data.newrow();//具有相同架构的行
69                             for (int j = row.firstcellnum; j < cellcount; j++)
70                             {
71                                 if (row.getcell(j) != null)
72                                 {
73                                     datarow[j] = row.getcell(j).tostring();
74                                 }
75                             }
76                             data.rows.add(datarow);
77                         }
78                     }
79                     return data;
80                 }
81                 catch (exception ex)
82                 {
83                     console.writeline("exception: " + ex.message);
84                     return null;
85                 }
86                 finally { fs.close(); fs.dispose(); }
87             }
88         }

 

测试代码:

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.data;
 6 
 7 using npoihelpertool;
 8 using bll;
 9 namespace consoleapplication1
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             datatable data = new datatable();
16             for (int i = 0; i < 5; ++i)
17             {
18                 data.columns.add("columns_" + i.tostring(), typeof(string));
19             }
20 
21             for (int i = 0; i < 10; ++i)
22             {
23                 datarow row = data.newrow();
24                 row["columns_0"] = "item0_" + i.tostring();
25                 row["columns_1"] = "item1_" + i.tostring();
26                 row["columns_2"] = "item2_" + i.tostring();
27                 row["columns_3"] = "item3_" + i.tostring();
28                 row["columns_4"] = "item4_" + i.tostring();
29                 data.rows.add(row);
30             }
31 
32             excelhelper h = new excelhelper();
33             datatable de = h.exceltodatatable(@"e:\myuser.xls", "sheet1", true);
34             int c = h.datatabletoexcel(data, @"e:\test.xls", "sheet1", true);
35             ilist<student> a = typeutil.tolist<student>(de);
36         }
37 
38     }
39     class student
40     {
41         public string id { get; set; }
42         public string name { get; set; }
43         public string nc { get; set; }
44     }
45 }