NPOI读取Excel文件

匿名 (未验证) 提交于 2019-12-02 22:06:11
 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     }
读取方法

文章来源: NPOI读取Excel文件
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!