码迷,mamicode.com
首页 > 其他好文 > 详细

封装一个ExcelHelper,方便将Excel直接转成Datatable对象

时间:2018-11-24 19:52:35      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:mat   space   odata   val   cell   oid   dna   name   array   

  1  public class ExcelHelper
  2     {
  3         /// <summary>
  4         /// Excel转换成DataTable
  5         /// </summary>
  6         /// <param name="excelFilePath">excel文件路径</param>
  7         /// <param name="sheetNum">sheet序号</param>
  8         /// <param name="headerRowNum">标题列序号</param>
  9         /// <returns></returns>
 10         public static DataTable ExcelToDataTable(string excelFilePath,int sheetNum=0,int headerRowNum=0)
 11         {
 12            
 13             IWorkbook workbook;
 14             DataTable dt;
 15             string extension = Path.GetExtension(excelFilePath).ToLower();
 16             try
 17             {              
 18                 using (FileStream fileStream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
 19                 {
 20                     if (extension == ".xlsx")
 21                     { workbook = new XSSFWorkbook(fileStream); }
 22                     else
 23                     { workbook = new HSSFWorkbook(fileStream); }
 24                     ISheet sheet = workbook.GetSheetAt(sheetNum);
 25                     dt = new DataTable(sheet.SheetName);
 26                     IRow headerRow = sheet.GetRow(headerRowNum);
 27                     string fieldName = "";
 28                     //ArrayList fieldArray = new ArrayList();
 29                     /*
 30                      增加标题列,author liwx 2016/08/25
 31                      */
 32                     for (int i = headerRow.FirstCellNum; i < headerRow.LastCellNum; i++)
 33                     {
 34                         if (headerRow.GetCell(i) != null)
 35                         {
 36                             fieldName = headerRow.GetCell(i).ToString().Trim();
 37                             //fieldArray.Add(fieldName);
 38                             DataColumn column = new DataColumn(fieldName);
 39                             dt.Columns.Add(column);
 40                         }
 41                         else
 42                         {
 43                             break;
 44                         }
 45                     }
 46 
 47                     DataRow dr;
 48                     IRow row;
 49                     ICell cell;
 50                     //short format;
 51                     for (int i = headerRowNum + 1; i <= sheet.LastRowNum; i++)
 52                     {
 53                         row = sheet.GetRow(i);
 54                         if (row != null)
 55                         {
 56                             dr = dt.NewRow();
 57                             for (int j = headerRow.FirstCellNum; j < headerRow.LastCellNum; j++)
 58                             {
 59                                 cell=row.GetCell(j);
 60                                 if (cell != null)
 61                                 {
 62                                     //format = cell.CellStyle.DataFormat;
 63                                     //if (format == 14 || format == 31 || format == 57 || format == 58)
 64                                     //    dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd");//日期转化格式如需要可解开
 65                                     dr[j] = cell.ToString().Trim() == "" ? null : cell.ToString().Trim();
 66                                 }
 67                                 else
 68                                 {
 69                                     dr[j] = null;
 70                                 }                               
 71                             }
 72                             dt.Rows.Add(dr);
 73                         }                       
 74                     }                   
 75                 }                
 76             }
 77             catch (Exception ex)
 78             {                
 79                 throw ex;
 80             }
 81             return dt;           
 82         }
 83         /// <summary>
 84         /// Excel转换成DataTable
 85         /// </summary>
 86         /// <param name="excelFilePath">excel文件路径</param>
 87         /// <param name="sheetName">sheet名称</param>
 88         /// <param name="headerRowNum">标题列序号</param>
 89         /// <returns></returns>
 90         public static DataTable ExcelToDataTable(string excelFilePath, string sheetName, int headerRowNum = 0)
 91         {
 92 
 93             IWorkbook workbook;
 94             DataTable dt;
 95             string extension = Path.GetExtension(excelFilePath).ToLower();
 96             try
 97             {
 98                 using (FileStream fileStream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
 99                 {
100                     if (extension == ".xlsx")
101                     { workbook = new XSSFWorkbook(fileStream); }
102                     else
103                     { workbook = new HSSFWorkbook(fileStream); }
104                     ISheet sheet;
105                     //如果有指定工作表名称
106                     if (!string.IsNullOrEmpty(sheetName))
107                     {
108                         sheet = workbook.GetSheet(sheetName);
109                         //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
110                         if (sheet == null)
111                         {
112                             sheet = workbook.GetSheetAt(0);
113                         }
114                     }
115                     else
116                     {
117                         //如果没有指定的sheetName,则尝试获取第一个sheet
118                         sheet = workbook.GetSheetAt(0);
119                     }
120 
121                     dt = new DataTable(sheet.SheetName);
122                     IRow headerRow = sheet.GetRow(headerRowNum);
123                     string fieldName = "";
124                     //ArrayList fieldArray = new ArrayList();
125                     /*
126                      增加标题列,author liwx 2016/08/25
127                      */
128                     for (int i = headerRow.FirstCellNum; i < headerRow.LastCellNum; i++)
129                     {
130                         if (headerRow.GetCell(i) != null)
131                         {
132                             fieldName = headerRow.GetCell(i).ToString().Trim();
133                             //fieldArray.Add(fieldName);
134                             DataColumn column = new DataColumn(fieldName);
135                             dt.Columns.Add(column);
136                         }
137                         else
138                         {
139                             break;
140                         }
141                     }
142 
143                     DataRow dr;
144                     IRow row;
145                     ICell cell;
146                     //short format;
147                     for (int i = headerRowNum + 1; i <= sheet.LastRowNum; i++)
148                     {
149                         row = sheet.GetRow(i);
150                         if (row != null)
151                         {
152                             dr = dt.NewRow();
153                             for (int j = headerRow.FirstCellNum; j < headerRow.LastCellNum; j++)
154                             {
155                                 cell = row.GetCell(j);
156                                 if (cell != null)
157                                 {
158                                     //format = cell.CellStyle.DataFormat;
159                                     //if (format == 14 || format == 31 || format == 57 || format == 58)
160                                     //    dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd");//日期转化格式如需要可解开
161                                     dr[j] = cell.ToString().Trim() == "" ? null : cell.ToString().Trim();
162                                 }
163                                 else
164                                 {
165                                     dr[j] = null;
166                                 }
167                             }
168                             dt.Rows.Add(dr);
169                         }
170                     }
171                 }
172             }
173             catch (Exception ex)
174             {
175                 throw ex;
176             }
177             return RemoveEmpty(dt);
178         }
179         /// <summary>
180         /// 获取Excel里Sheet总数
181         /// </summary>
182         /// <param name="excelFilePath"></param>
183         /// <returns></returns>
184         public static int GetExcelSheetTotal(string excelFilePath)
185         {
186             IWorkbook workbook;
187             DataTable dt;
188             string extension = Path.GetExtension(excelFilePath).ToLower();
189             try
190             {
191                 using (FileStream fileStream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
192                 {
193                     if (extension == ".xlsx")
194                     { workbook = new XSSFWorkbook(fileStream); }
195                     else
196                     { workbook = new HSSFWorkbook(fileStream); }
197                     return workbook.NumberOfSheets;
198                 }
199             }
200             catch (Exception ex)
201             {
202                 throw ex;
203             }
204         }
205 
206         /// <summary>
207         /// 将datatable导入到exel
208         /// </summary>
209         /// <param name="datatemp"></param>
210         /// <param name="fileName"></param>
211         ///<param name="removeEmpty">是否去除所有值都为空的列</param>
212         /// <returns></returns>
213         public static int DataTableToExcel(DataTable datatemp, string fileName,bool removeEmpty=true)
214         {
215             DataTable data = removeEmpty? RemoveEmpty(datatemp): datatemp;
216             bool isColumnWritten = true;
217             int i = 0;
218             int j = 0;
219             int count = 0;
220             ISheet sheet = null;
221             IWorkbook workbook = null;
222             using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
223             {
224                 if (fileName.IndexOf(".xlsx") > 0) // 2007版本
225                     workbook = new XSSFWorkbook();
226                 else if (fileName.IndexOf(".xls") > 0) // 2003版本
227                     workbook = new HSSFWorkbook();
228 
229                 try
230                 {
231                     if (workbook != null)
232                     {
233                         sheet = workbook.CreateSheet("Sheet1");
234                     }
235                     else
236                     {
237                         return -1;
238                     }
239 
240                     if (isColumnWritten == true) //写入DataTable的列名
241                     {
242                         IRow row = sheet.CreateRow(0);
243                         for (j = 0; j < data.Columns.Count; ++j)
244                         {
245                             row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
246                         }
247                         count = 1;
248                     }
249                     else
250                     {
251                         count = 0;
252                     }
253 
254                     for (i = 0; i < data.Rows.Count; ++i)
255                     {
256                         IRow row = sheet.CreateRow(count);
257                         for (j = 0; j < data.Columns.Count; ++j)
258                         {
259                             row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
260                         }
261                         ++count;
262                     }
263                     workbook.Write(fs); //写入到excel
264                     return count;
265                 }
266                 catch (Exception ex)
267                 {
268                     Console.WriteLine("Exception: " + ex.Message);
269                     return -1;
270                 }
271             }
272         }
273 
274 
275 
276         /// <summary>
277         /// Excel导出成内存流
278         /// </summary>
279         /// <param name="data"></param>
280         /// <returns></returns>
281         public static MemoryStream DataTableToExcel(DataTable data)
282         {
283             bool isColumnWritten = true;
284             int i = 0;
285             int j = 0;
286             int count = 0;
287             IWorkbook workbook =new HSSFWorkbook();
288             try
289             {
290                 //添加一个sheet
291                 ISheet sheet = workbook.CreateSheet("Sheet1");
292                 //将数据逐步写入sheet1各个行
293                 if (isColumnWritten == true) //写入DataTable的列名
294                 {
295                     IRow row = sheet.CreateRow(0);
296                     for (j = 0; j < data.Columns.Count; ++j)
297                     {
298                         row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
299                     }
300                     count = 1;
301                 }
302                 else
303                 {
304                     count = 0;
305                 }
306 
307                 for (i = 0; i < data.Rows.Count; ++i)
308                 {
309                     IRow row = sheet.CreateRow(count);
310                     for (j = 0; j < data.Columns.Count; ++j)
311                     {
312                         row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
313                     }
314                     ++count;
315                 }
316                 // 写入到客户端 
317                 MemoryStream ms = new System.IO.MemoryStream();
318                 workbook.Write(ms);
319                 ms.Seek(0, SeekOrigin.Begin);
320                 return ms;
321             }
322             catch (Exception ex)
323             {
324                 throw ex;
325                 Console.WriteLine("Exception: " + ex.Message);
326                 return null;
327             }                
328         }
329 
330 
331 
332 
333         /// <summary>
334         /// Excel导出成内存流
335         /// </summary>
336         /// <param name="data"></param>
337         /// <returns></returns>
338         public static MemoryStream DataTableToExcel(List<DataTable> dtList,List<string> nameList)
339         {
340             IWorkbook workbook = new HSSFWorkbook();
341             try
342             {
343                 var data = dtList[0];
344                 for (var i=0;i<dtList.Count();i++) { 
345                     ISheet sheet=string.IsNullOrWhiteSpace(nameList[i]) ?workbook.CreateSheet("Sheet"+(i+1)):workbook.CreateSheet(nameList[i]);
346                       WriteSheet(dtList[i],sheet);              
347                 }              
348                 // 写入到客户端 
349                 MemoryStream ms = new System.IO.MemoryStream();
350                 workbook.Write(ms);
351                 ms.Seek(0, SeekOrigin.Begin);
352                 return ms;
353             }
354             catch (Exception ex)
355             {
356                 throw ex;
357                 Console.WriteLine("Exception: " + ex.Message);
358                 return null;
359             }
360         }
361 
362 
363 
364         private static void WriteSheet(DataTable data,ISheet sheet, bool isColumnWritten=true) {
365             int i = 0;
366             int j = 0;
367             int count = 0;
368             //将数据逐步写入sheet1各个行
369             if (isColumnWritten == true) //写入DataTable的列名
370             {
371                 IRow row = sheet.CreateRow(0);
372                 for (j = 0; j < data.Columns.Count; ++j)
373                 {
374                     row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
375                 }
376                 count = 1;
377             }
378             else
379             {
380                 count = 0;
381             }
382 
383             for (i = 0; i < data.Rows.Count; ++i)
384             {
385                 IRow row = sheet.CreateRow(count);
386                 for (j = 0; j < data.Columns.Count; ++j)
387                 {
388                     row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
389                 }
390                 ++count;
391             }
392         
393         }
394         /// <summary>
395         /// 去除空行
396         /// </summary>
397         /// <param name="dtr"></param>
398         /// <returns></returns>
399         protected static DataTable RemoveEmpty(DataTable dtr)
400         {
401             DataTable dt = dtr;
402             List<DataRow> removelist = new List<DataRow>();
403             for (int i = 0; i < dt.Rows.Count; i++)
404             {
405                 bool IsNull = true;
406                 for (int j = 0; j < dt.Columns.Count; j++)
407                 {
408                     if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
409                     {
410                         IsNull = false;
411                     }
412                 }
413                 if (IsNull)
414                 {
415                     removelist.Add(dt.Rows[i]);
416                 }
417             }
418             for (int i = 0; i < removelist.Count; i++)
419             {
420                 dt.Rows.Remove(removelist[i]);
421             }
422             return dt;
423         }
424     }

 

封装一个ExcelHelper,方便将Excel直接转成Datatable对象

标签:mat   space   odata   val   cell   oid   dna   name   array   

原文地址:https://www.cnblogs.com/zzlblog/p/10013069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!