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

  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     }

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

时间: 2024-10-12 21:22:37

封装一个ExcelHelper,方便将Excel直接转成Datatable对象的相关文章

将Excel表格数据转换成Datatable

/// <summary> /// 将Excel表格数据转换成Datatable /// </summary> /// <param name="fileUrl">文件地址</param> /// <param name="table">table命名</param> /// <returns></returns> public DataTable GetExcelDat

将Excel表格转成DataTable

直接贴上代码: public DataSet ExecleDs(string filenameurl) { DataSet ds = new DataSet(); //不同版本的Excel连接字符串不同 string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 12.0; HDR=Ye

我写的一个ExcelHelper通用类,可用于读取或生成数据

读取或生成EXCEL数据的方法有很多,一般常见的有: 1.通过OFFICE EXCEL组件,优点:读取与生成EXCEL文件方便,缺点:服务器上必须安装OFFICE软件,且进程无法及时释放 2.通过第三方组件(比如:NPOI),优点:无需安装OFFICE软件,缺点:需要引入第三方组件,当然这个还是比较强的 3.通过把EXCEL当成数据库,连接后运用SQL语句读取,写入的话就自行拼接成HTML表格,优点:无需另外的组件,缺点:需要会SQL及拼接HTML表格较麻烦: 三种方法我都有用过,若开发BS网站

开张了。。第一次,就发一个简单的导出excel

直接开始吧...不墨迹了. 这里我就不贴代码了..直接截图,,,如果感兴趣,就手敲代码..然后图片我都会写上注释的. 我主要开发是MVC模式开发.View是CSHTML 先是前台吧 写一个按钮就行了..然后给一个onclick事件 如: <input type="button" class="readd" id="outexcel" value="导出"> 前台给显示页面加<td><input n

Directx11学习笔记【四】 封装一个简单的Dx11DemoBase

根据前面两个笔记的内容,我们来封装一个简单的基类,方便以后的使用. 代码和前面类似,没有什么新的内容,直接看代码吧(由于代码上次都注释了,这次代码就没怎么写注释o(╯□╰)o) Dx11DemoBase.h Dx11DemoBase.h #pragma once #include <d3d11.h> #include <D3DX11.h> #include <DxErr.h> class Dx11DemoBase { public: Dx11DemoBase(); vi

封装一个类似jquery的ajax方法

//封装一个类似jquery的ajax方法,当传入参数,就可以发送ajax请求 //参数格式如下{ // type:"get"/"post", // dataType:"json"/"jsonp", // url:"地址", // data:{key:value} // success:function(){ // } // } //还需要一个跨域方法,可以访问远程服务器的数据 function myAja

C 封装一个通用链表 和 一个简单字符串开发库

引言 这里需要分享的是一个 简单字符串库和 链表的基库,代码也许用到特定技巧.有时候回想一下, 如果我读书的时候有人告诉我这些关于C开发的积淀, 那么会走的多直啊.刚参加工作的时候做桌面开发, 服务是C++写,界面是C#写.那时候刚进去评级我是中级,因为他问我关于系统锁和信号量都答出来.开发一段 时间,写C#也写的很溜.后面招我那个人让我转行就写C++和php,那时候就开始学习C++有关知识. 后面去四川工作了,开发安卓,用eclipse + java语法 + android jdk,开发前端,

[js高手之路]javascript腾讯面试题学习封装一个简易的异步队列

这道js的面试题,是这样的,页面上有一个按钮,一个ul,点击按钮的时候,每隔1秒钟向ul的后面追加一个li, 一共追加10个,li的内容从0开始技术( 0, 1, 2, ....9 ),首先我们用闭包封装一个创建li元素的函数. 1 var create = (function(){ 2 var count = 0; 3 return function(){ 4 var oLi = document.createElement( "li" ); 5 oLi.innerHTML = co

封装一个Ajax工具函数

/*封装一个ajax工具函数*/ window.$ = {}; /*通过$定义一个ajax函数*/ /* * 1. type   string   请求的方式  默认是get * 2. url    string   请求地址  接口地址 * 3. async  boolean  默认的是true * 4. data   object   {}请求数据 * * 5.success function  成功回调函数 * 6.error   function  失败的回调函数 * */ $.ajax