NPOI导入EXCEL

最近有个项目需要用到excel导入,要求是excel有哪些字段不固定,对应到数据库的字段需要动态配置,而且客户可以随意修改,在网上也找了一些方法,也做过一些测试,最终选择NPOI,于此相关的帖子网上也有很多,在此,我只是记录下研究的成果,如果代码有什么问题,还请大家不吝赐教。。。。以下只是读取excel部分。。。

  1 public class DataTableRenderToExcel
  2     {
  3         public DataTableRenderToExcel()
  4         {
  5             //
  6             // TODO: 在此加入建構函式的程式碼
  7             //
  8         }
  9         static private IWorkbook workbook = null;
 10         static private ISheet sheet = null;
 11         static private DataTable dt_data = null;
 12 
 13         static private string _filepath;
 14         static public string FilePath
 15         {
 16             set { _filepath = value; }
 17             get { return _filepath; }
 18         }
 19         static private string _sheetname;
 20         static public string SheetName
 21         {
 22             set { _sheetname = value; }
 23             get { return _sheetname; }
 24         }
 25 
 26 
 27         #region NPOI导入EXCEL
 28         /// <summary>
 29         /// 创建工作簿
 30         /// </summary>
 31         private static IWorkbook CreateWorkBook()
 32         {
 33             try
 34             {
 35                 using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
 36                 {
 37                     if (FilePath.IndexOf(".xlsx") > 0)    // 2007或2010版本
 38                         return new XSSFWorkbook(fs);
 39                     else
 40                         return new HSSFWorkbook(fs);    // 2003版本
 41                 }
 42             }
 43             catch (Exception ex)
 44             {
 45                 throw ex;
 46             }
 47         }
 48         /// <summary>
 49         /// 获取EXCEL工作表sheet集合
 50         /// </summary>
 51         /// <param name="fileName"></param>
 52         /// <returns></returns>
 53         public static List<string> ExcelSheetToDT()
 54         {
 55             List<string> sheetName = new List<string>();
 56             try
 57             {
 58                 if (workbook == null)
 59                     workbook = CreateWorkBook();
 60 
 61                 int sheetCount = workbook.NumberOfSheets;
 62 
 63                 for (int i = 0; i < sheetCount; i++)
 64                 {
 65                     sheetName.Add(workbook.GetSheetName(i));
 66                 }
 67             }
 68             catch (Exception ex)
 69             {
 70                 throw ex;
 71             }
 72             return sheetName;
 73         }
 74         /// <summary>
 75         /// 返回EXCEL工作簿sheet
 76         /// </summary>
 77         /// <param name="sheetName"></param>
 78         /// <returns></returns>
 79         private static ISheet GetExcelSheet()
 80         {
 81             try
 82             {
 83                 if (workbook == null)
 84                     workbook = CreateWorkBook();
 85 
 86                 if (SheetName == string.Empty)
 87                     SheetName = ExcelSheetToDT()[0].ToString();
 88 
 89                 return workbook.GetSheet(SheetName);
 90             }
 91             catch (Exception ex)
 92             {
 93                 throw ex;
 94             }
 95         }
 96         /// <summary>
 97         /// 获取EXCEL列名
 98         /// </summary>
 99         /// <param name="sheetName"></param>
100         /// <param name="firstRowNum"></param>
101         /// <returns></returns>
102         public static DataTable GetExcelHeader()
103         {
104             DataTable dt = new DataTable();
105             dt_data = new DataTable();
106             try
107             {
108                 if (sheet == null)
109                     sheet = GetExcelSheet();
110 
111                 dt.Columns.Add("COLUMNS", typeof(string));
112                 IRow header = sheet.GetRow(sheet.FirstRowNum);
113                 for (int i = header.FirstCellNum, len = header.LastCellNum; i < len; i++)
114                 {
115                     object obj = GetValueTypeForXlsx(header.GetCell(i) as XSSFCell);
116                     if (obj == null || obj.ToString() == string.Empty)
117                     {
118                         dt.Rows.Add(new DataColumn("Columns" + i.ToString()));
119                         dt_data.Columns.Add(new DataColumn("Columns" + i.ToString()));
120                     }
121                     else
122                     {
123                         dt.Rows.Add(new DataColumn(obj.ToString()));
124                         dt_data.Columns.Add(new DataColumn(obj.ToString()));
125                     }
126                 }
127             }
128             catch (Exception ex)
129             {
130                 throw ex;
131             }
132             return dt;
133         }
134         /// <summary>
135         /// 获取EXCEL数据
136         /// </summary>
137         /// <returns></returns>
138         public static DataTable GetExcelData()
139         {
140             try
141             {
142                 if (sheet == null)
143                     sheet = GetExcelSheet();
144                 for (int i = sheet.FirstRowNum + 1, len = sheet.LastRowNum; i <= len; i++)
145                 {
146                     DataRow dr = dt_data.NewRow();
147                     bool hasValue = false;
148                     for (int j = 0; j < sheet.GetRow(sheet.FirstRowNum).LastCellNum; j++)
149                     {
150                         dr[j] = GetValueTypeForXlsx(sheet.GetRow(i).GetCell(j) as XSSFCell);
151                         if (dr[j] != null && dr[j].ToString() != string.Empty)
152                             hasValue = true;
153                     }
154                     if (hasValue)
155                     {
156                         dt_data.Rows.Add(dr);
157                     }
158                 }
159             }
160             catch (Exception ex)
161             {
162                 throw ex;
163             }
164             return dt_data;
165         }
166 
167         /// <summary>
168         /// 获取数据类型
169         /// </summary>
170         /// <param name="cell"></param>
171         /// <returns></returns>
172         private static object GetValueTypeForXlsx(XSSFCell cell)
173         {
174             if (cell == null)
175                 return null;
176             switch (cell.CellType)
177             {
178                 case CellType.Blank:
179                     return null;
180                 case CellType.Boolean:
181                     return cell.BooleanCellValue;
182                 case CellType.Numeric:
183                     return cell.NumericCellValue;
184                 case CellType.Error:
185                     return cell.ErrorCellValue;
186                 case CellType.Formula:
187                     return cell.CellFormula;
188                 case CellType.String:
189                     return cell.StringCellValue;
190                 default:
191                     return cell.StringCellValue;
192             }
193         }
194         #endregion
195     }
View Code

 

posted on 2014-09-05 14:49  luole  阅读(208)  评论(0编辑  收藏  举报

导航