欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

NPOI读取Excel文件

程序员文章站 2022-12-15 23:50:56
1 public class ExcelOperator 2 { 3 public static List Read(string fileName) 4 { 5 List tables = new List(); 6 if (!Fi ......
NPOI读取Excel文件
 1 public class exceloperator
 2     {
 3         public static list<datatable> read(string filename)
 4         {
 5             list<datatable> tables = new list<datatable>();
 6             if (!file.exists(filename))
 7                 return tables;
 8             var fs = new filestream(filename, filemode.open, fileaccess.read);
 9             iworkbook workbook = null;
10             if (filename.indexof(".xlsx") > 0)
11             {
12                 // 2007版本
13                 workbook = new xssfworkbook(fs);
14             }
15             else if (filename.indexof(".xls") > 0)
16             {
17                 // 2003版本
18                 workbook = new hssfworkbook(fs);
19             }
20 
21             var workbooks = workbook.getenumerator();
22             while (workbooks.movenext())
23             {
24                 isheet sheet = workbooks.current as isheet;
25                 datatable dt = new datatable(sheet.sheetname);
26                 var rows = sheet.getrowenumerator();
27                 while (rows.movenext())
28                 {
29                     irow row = rows.current as irow;
30                     if (row.rownum == 0)
31                     {
32                         row.cells.foreach(cell =>
33                         {
34                             dt.columns.add(cell.stringcellvalue);
35                         });
36                     }
37                     else
38                     {
39                         var dr = dt.newrow();
40                         for (int i = 0; i < row.cells.count; i++)
41                         {
42                             dr[i] = row.cells[i].tostring();
43                         }
44                         dt.rows.add(dr);
45                     }
46                 }
47 
48                 tables.add(dt);
49             }
50             return tables;
51         }
52     }
读取方法