VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之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     }
复制代码

相关教程