NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters

  1 /*******************************************************************
  2  * 版权所有: 
  3  * 类 名 称:ExcelHelper
  4  * 作    者:zk
  5  * 电子邮箱: 
  6  * 创建日期:2012/2/25 10:17:21 
  7  * 修改描述:从excel导入datatable时,可以导入日期类型。
  8  *           但对excel中的日期类型有一定要求,要求至少是yyyy/mm/dd类型日期; *           
  9  * 修改描述:将datatable导入excel中,对类型为字符串的数字进行处理,
 10  *           导出数字为double类型;
 11  * 
 12  * 
 13  * *******************************************************************/
 14 using System;
 15 using System.Collections.Generic;
 16 using System.Data;
 17 using System.IO;
 18 using System.Text;
 19 using System.Web;
 20 using NPOI;
 21 using NPOI.HPSF;
 22 using NPOI.HSSF;
 23 using NPOI.HSSF.Record.Formula.Eval;
 24 using NPOI.HSSF.UserModel;
 25 using NPOI.HSSF.Util;
 26 using NPOI.POIFS;
 27 using NPOI.SS.UserModel;
 28 using NPOI.Util;
 29 using NPOI.SS;
 30 using NPOI.DDF;
 31 using NPOI.SS.Util;
 32 using System.Collections;
 33 using System.Text.RegularExpressions;
 34  
 35 namespace chuzhang
 36 {
 37     public static class ExcelHelper
 38     {
 39         //private static WriteLog wl = new WriteLog();a
 40          
 41  
 42         #region 从datatable中将数据导出到excel
 43         /// <summary>
 44         /// DataTable导出到Excel的MemoryStream
 45         /// </summary>
 46         /// <param name="dtSource">源DataTable</param>
 47         /// <param name="strHeaderText">表头文本</param>
 48      public    static MemoryStream ExportDT(DataTable dtSource, string strHeaderText)
 49         {
 50             HSSFWorkbook workbook = new HSSFWorkbook();
 51             HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
 52  
 53             #region 右击文件 属性信息
 54  
 55             //{
 56             //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
 57             //    dsi.Company = "http://www.yongfa365.com/";
 58             //    workbook.DocumentSummaryInformation = dsi;
 59  
 60             //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
 61             //    si.Author = "柳永法"; //填加xls文件作者信息
 62             //    si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
 63             //    si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
 64             //    si.Comments = "说明信息"; //填加xls文件作者信息
 65             //    si.Title = "NPOI测试"; //填加xls文件标题信息
 66             //    si.Subject = "NPOI测试Demo"; //填加文件主题信息
 67             //    si.CreateDateTime = DateTime.Now;
 68             //    workbook.SummaryInformation = si;
 69             //}
 70  
 71             #endregion
 72  
 73             HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
 74             HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
 75             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
 76  
 77             //取得列宽
 78             int[] arrColWidth = new int[dtSource.Columns.Count];
 79             foreach (DataColumn item in dtSource.Columns)
 80             {
 81                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
 82             }
 83             for (int i = 0; i < dtSource.Rows.Count; i++)
 84             {
 85                 for (int j = 0; j < dtSource.Columns.Count; j++)
 86                 {
 87                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
 88                     if (intTemp > arrColWidth[j])
 89                     {
 90                         arrColWidth[j] = intTemp;
 91                     }
 92                 }
 93             }
 94             int rowIndex = 0;
 95  
 96             foreach (DataRow row in dtSource.Rows)
 97             {
 98                 #region 新建表,填充表头,填充列头,样式
 99  
100                 if (rowIndex == 65535 || rowIndex == 0)
101                 {
102                     if (rowIndex != 0)
103                     {
104                         sheet = workbook.CreateSheet() as HSSFSheet;
105                     }
106  
107                     #region 表头及样式
108  
109                     {
110                         HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
111                         headerRow.HeightInPoints = 25;
112                         headerRow.CreateCell(0).SetCellValue(strHeaderText);
113  
114                         HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
115                         headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
116                         HSSFFont font = workbook.CreateFont() as HSSFFont;
117                         font.FontHeightInPoints = 20;
118                         font.Boldweight = 700;
119                         headStyle.SetFont(font);
120  
121                         headerRow.GetCell(0).CellStyle = headStyle;
122  
123                         sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
124                         //headerRow.Dispose();
125                     }
126  
127                     #endregion
128  
129  
130                     #region 列头及样式
131  
132                     {
133                         HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
134  
135  
136                         HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
137                         headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
138                         HSSFFont font = workbook.CreateFont() as HSSFFont;
139                         font.FontHeightInPoints = 10;
140                         font.Boldweight = 700;
141                         headStyle.SetFont(font);
142  
143  
144                         foreach (DataColumn column in dtSource.Columns)
145                         {
146                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
147                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
148  
149                             //设置列宽
150                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1)*256);
151  
152                         }
153                         //headerRow.Dispose();
154                     }
155  
156                     #endregion
157  
158                     rowIndex = 2;
159                 }
160  
161                 #endregion
162  
163                 #region 填充内容
164  
165                 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
166                 foreach (DataColumn column in dtSource.Columns)
167                 {
168                     HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
169  
170                     string drValue = row[column].ToString();
171  
172                     switch (column.DataType.ToString())
173                     {
174                         case "System.String": //字符串类型
175                             double result;
176                             if(isNumeric(drValue,out result))
177                             {
178  
179                                 double.TryParse(drValue, out result);
180                                 newCell.SetCellValue(result);
181                                 break;
182                             }
183                             else
184                             {
185                                 newCell.SetCellValue(drValue);
186                                 break;
187                             }
188                              
189                         case "System.DateTime": //日期类型
190                             DateTime dateV;
191                             DateTime.TryParse(drValue, out dateV);
192                             newCell.SetCellValue(dateV);
193  
194                             newCell.CellStyle = dateStyle; //格式化显示
195                             break;
196                         case "System.Boolean": //布尔型
197                             bool boolV = false;
198                             bool.TryParse(drValue, out boolV);
199                             newCell.SetCellValue(boolV);
200                             break;
201                         case "System.Int16": //整型
202                         case "System.Int32":
203                         case "System.Int64":
204                         case "System.Byte":
205                             int intV = 0;
206                             int.TryParse(drValue, out intV);
207                             newCell.SetCellValue(intV);
208                             break;
209                         case "System.Decimal": //浮点型
210                         case "System.Double":
211                             double doubV = 0;
212                             double.TryParse(drValue, out doubV);
213                             newCell.SetCellValue(doubV);
214                             break;
215                         case "System.DBNull": //空值处理
216                             newCell.SetCellValue("");
217                             break;
218                         default:
219                             newCell.SetCellValue("");
220                             break;
221                     }
222  
223                 }
224  
225                 #endregion
226  
227                 rowIndex++;
228             }
229             using (MemoryStream ms = new MemoryStream())
230             {
231                 workbook.Write(ms);
232                 ms.Flush();
233                 ms.Position = 0;
234  
235                 sheet.Dispose();
236                 workbook.Dispose();
237  
238                 return ms;
239             }
240         }
241          
242         /// <summary>
243         /// DataTable导出到Excel文件
244         /// </summary>
245         /// <param name="dtSource">源DataTable</param>
246         /// <param name="strHeaderText">表头文本</param>
247         /// <param name="strFileName">保存位置</param>
248         public  static  void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
249         {
250             using (MemoryStream ms = ExportDT(dtSource, strHeaderText))
251             {
252                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
253                 {
254                     byte[] data = ms.ToArray();
255                     fs.Write(data, 0, data.Length);
256                     fs.Flush();
257                 }
258             }
259         }
260 #endregion
261  
262         #region 从excel中将数据导出到datatable
263         /// <summary>读取excel
264         /// 默认第一行为标头
265         /// </summary>
266         /// <param name="strFileName">excel文档路径</param>
267         /// <returns></returns>
268         public static DataTable ImportExceltoDt(string strFileName)
269         {
270             DataTable dt = new DataTable();
271             HSSFWorkbook hssfworkbook;
272             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
273             {
274                 hssfworkbook = new HSSFWorkbook(file);
275             }
276             HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
277             dt = ImportDt(sheet, 0, true);
278             return dt;
279         }
280  
281         /// <summary>
282         /// 读取excel
283         /// </summary>
284         /// <param name="strFileName">excel文件路径</param>
285         /// <param name="sheet">需要导出的sheet</param>
286         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
287         /// <returns></returns>
288         public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex)
289         {
290             HSSFWorkbook workbook;
291             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
292             {
293                 workbook = new HSSFWorkbook(file);
294             }
295             HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
296             DataTable table = new DataTable();
297             table = ImportDt(sheet, HeaderRowIndex, true);
298             //ExcelFileStream.Close();
299             workbook = null;
300             sheet = null;
301             return table;
302         }
303  
304         /// <summary>
305         /// 读取excel
306         /// </summary>
307         /// <param name="strFileName">excel文件路径</param>
308         /// <param name="sheet">需要导出的sheet序号</param>
309         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
310         /// <returns></returns>
311         public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex)
312         {
313             HSSFWorkbook workbook;
314             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
315             {
316                 workbook = new HSSFWorkbook(file);
317             }
318             HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
319             DataTable table = new DataTable();
320             table = ImportDt(sheet, HeaderRowIndex, true);
321             //ExcelFileStream.Close();
322             workbook = null;
323             sheet = null;
324             return table;
325         }
326  
327         /// <summary>
328         /// 读取excel
329         /// </summary>
330         /// <param name="strFileName">excel文件路径</param>
331         /// <param name="sheet">需要导出的sheet</param>
332         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
333         /// <returns></returns>
334         public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader)
335         {
336             HSSFWorkbook workbook;
337             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
338             {
339                 workbook = new HSSFWorkbook(file);
340             }
341             HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
342             DataTable table = new DataTable();
343             table = ImportDt(sheet, HeaderRowIndex, needHeader);
344             //ExcelFileStream.Close();
345             workbook = null;
346             sheet = null;
347             return table;
348         }
349  
350         /// <summary>
351         /// 读取excel
352         /// </summary>
353         /// <param name="strFileName">excel文件路径</param>
354         /// <param name="sheet">需要导出的sheet序号</param>
355         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
356         /// <returns></returns>
357         public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
358         {
359             HSSFWorkbook workbook;
360             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
361             {
362                 workbook = new HSSFWorkbook(file);
363             }
364             HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
365             DataTable table = new DataTable();
366             table = ImportDt(sheet, HeaderRowIndex, needHeader);
367             //ExcelFileStream.Close();
368             workbook = null;
369             sheet = null;
370             return table;
371         }
372           
373         /// <summary>
374         /// 将制定sheet中的数据导出到datatable中
375         /// </summary>
376         /// <param name="sheet">需要导出的sheet</param>
377         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
378         /// <returns></returns>
379         static DataTable ImportDt(HSSFSheet sheet, int HeaderRowIndex,bool needHeader)
380         {
381             DataTable table = new DataTable();
382             HSSFRow headerRow;
383             int cellCount;
384             try
385             {
386                 if (HeaderRowIndex < 0 || !needHeader)
387                 {
388                     headerRow = sheet.GetRow(0) as HSSFRow;
389                     cellCount = headerRow.LastCellNum;
390  
391                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
392                     {
393                         DataColumn column = new DataColumn(Convert.ToString(i));
394                         table.Columns.Add(column);
395                     }
396                 }
397                 else
398                 {
399                     headerRow = sheet.GetRow(HeaderRowIndex) as HSSFRow;
400                     cellCount = headerRow.LastCellNum;
401  
402                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
403                     {
404                         if (headerRow.GetCell(i) == null)
405                         {
406                             if(table.Columns.IndexOf(Convert.ToString(i)) > 0)
407                             {
408                                 DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
409                                 table.Columns.Add(column); 
410                             }
411                             else
412                             {
413                                 DataColumn column = new DataColumn(Convert.ToString(i));
414                                 table.Columns.Add(column);
415                             }
416                              
417                         }
418                         else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
419                         {
420                             DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
421                             table.Columns.Add(column);
422                         }
423                         else
424                         {
425                             DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
426                             table.Columns.Add(column);
427                         }
428                     }
429                 }
430                 int rowCount = sheet.LastRowNum;
431                 for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
432                 {
433                     try
434                     {
435                         HSSFRow row;
436                         if (sheet.GetRow(i) == null)
437                         {
438                             row = sheet.CreateRow(i) as HSSFRow;
439                         }
440                         else
441                         {
442                             row = sheet.GetRow(i) as HSSFRow;
443                         }
444  
445                         DataRow dataRow = table.NewRow();
446  
447                         for (int j = row.FirstCellNum; j <= cellCount; j++)
448                         {
449                             try
450                             {
451                                 if (row.GetCell(j) != null)
452                                 {
453                                     switch (row.GetCell(j).CellType)
454                                     {
455                                         case CellType.STRING:
456                                             string str = row.GetCell(j).StringCellValue;
457                                             if (str != null && str.Length > 0)
458                                             {
459                                                 dataRow[j] = str.ToString();
460                                             }
461                                             else
462                                             {
463                                                 dataRow[j] = null;
464                                             }
465                                             break;
466                                         case CellType.NUMERIC:
467                                             if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
468                                             {
469                                                 dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
470                                             }
471                                             else
472                                             {
473                                                 dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
474                                             }
475                                             break;
476                                         case CellType.BOOLEAN:
477                                             dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
478                                             break;
479                                         case CellType.ERROR:
480                                             dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
481                                             break;
482                                         case CellType.FORMULA:
483                                             switch (row.GetCell(j).CachedFormulaResultType)
484                                             {
485                                                 case CellType.STRING:
486                                                     string strFORMULA = row.GetCell(j).StringCellValue;
487                                                     if (strFORMULA != null && strFORMULA.Length > 0)
488                                                     {
489                                                         dataRow[j] = strFORMULA.ToString();
490                                                     }
491                                                     else
492                                                     {
493                                                         dataRow[j] = null;
494                                                     }
495                                                     break;
496                                                 case CellType.NUMERIC:
497                                                     dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
498                                                     break;
499                                                 case CellType.BOOLEAN:
500                                                     dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
501                                                     break;
502                                                 case CellType.ERROR:
503                                                     dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
504                                                     break;
505                                                 default:
506                                                     dataRow[j] = "";
507                                                     break;
508                                             }
509                                             break;
510                                         default:
511                                             dataRow[j] = "";
512                                             break;
513                                     }
514                                 }
515                             }
516                             catch (Exception exception)
517                             {
518                                 //wl.WriteLogs(exception.ToString());
519                             }
520                         }
521                         table.Rows.Add(dataRow);
522                     }
523                     catch (Exception exception)
524                     {
525                         //wl.WriteLogs(exception.ToString());
526                     }
527                 }
528             }
529             catch (Exception exception)
530             {
531                 //wl.WriteLogs(exception.ToString());
532             }
533             return table;
534         }
535         #endregion 
536  
537         #region 更新excel中的数据
538         /// <summary>
539         /// 更新Excel表格
540         /// </summary>
541         /// <param name="outputFile">需更新的excel表格路径</param>
542         /// <param name="sheetname">sheet名</param>
543         /// <param name="updateData">需更新的数据</param>
544         /// <param name="coluid">需更新的列号</param>
545         /// <param name="rowid">需更新的开始行号</param>
546         public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid)
547         {
548             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
549  
550             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
551             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
552             for (int i = 0; i < updateData.Length; i++)
553             {
554                 try
555                 {
556                     if(sheet1.GetRow(i+rowid) == null)
557                     {
558                         sheet1.CreateRow(i + rowid);
559                     }
560                     if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
561                     {
562                         sheet1.GetRow(i + rowid).CreateCell(coluid);
563                     }
564                      
565                     sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
566                 }
567                 catch (Exception ex)
568                 {
569                    // wl.WriteLogs(ex.ToString());
570                     throw;
571                 }
572             }
573             try
574             {
575                 readfile.Close();
576                 FileStream writefile = new FileStream(outputFile, FileMode.Create,FileAccess.Write);
577                 hssfworkbook.Write(writefile);
578                 writefile.Close();
579             }
580             catch (Exception ex)
581             {
582                // wl.WriteLogs(ex.ToString());
583             }
584              
585         }
586  
587         /// <summary>
588         /// 更新Excel表格
589         /// </summary>
590         /// <param name="outputFile">需更新的excel表格路径</param>
591         /// <param name="sheetname">sheet名</param>
592         /// <param name="updateData">需更新的数据</param>
593         /// <param name="coluids">需更新的列号</param>
594         /// <param name="rowid">需更新的开始行号</param>
595         public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int [] coluids, int rowid)
596         {
597             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
598  
599             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
600             readfile.Close();
601             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
602             for (int j = 0; j < coluids.Length; j++)
603             {
604                 for (int i = 0; i < updateData[j].Length; i++)
605                 {
606                     try
607                     {
608                         if (sheet1.GetRow(i + rowid) == null)
609                         {
610                             sheet1.CreateRow(i + rowid);
611                         }
612                         if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
613                         {
614                             sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
615                         }
616                         sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
617                     }
618                     catch (Exception ex)
619                     {
620                        // wl.WriteLogs(ex.ToString());
621                     }
622                 }
623             }
624             try
625             {
626                 FileStream writefile = new FileStream(outputFile, FileMode.Create);
627                 hssfworkbook.Write(writefile);
628                 writefile.Close();
629             }
630             catch (Exception ex)
631             {
632                 //wl.WriteLogs(ex.ToString());
633             }
634         }
635  
636         /// <summary>
637         /// 更新Excel表格
638         /// </summary>
639         /// <param name="outputFile">需更新的excel表格路径</param>
640         /// <param name="sheetname">sheet名</param>
641         /// <param name="updateData">需更新的数据</param>
642         /// <param name="coluid">需更新的列号</param>
643         /// <param name="rowid">需更新的开始行号</param>
644         public static void UpdateExcel(string outputFile, string sheetname, double [] updateData, int coluid, int rowid)
645         {
646             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
647  
648             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
649             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
650             for (int i = 0; i < updateData.Length; i++)
651             {
652                 try
653                 {
654                     if (sheet1.GetRow(i + rowid) == null)
655                     {
656                         sheet1.CreateRow(i + rowid);
657                     }
658                     if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
659                     {
660                         sheet1.GetRow(i + rowid).CreateCell(coluid);
661                     }
662  
663                     sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
664                 }
665                 catch (Exception ex)
666                 {
667                     //wl.WriteLogs(ex.ToString());
668                     throw;
669                 }
670             }
671             try
672             {
673                 readfile.Close();
674                 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
675                 hssfworkbook.Write(writefile);
676                 writefile.Close();
677             }
678             catch (Exception ex)
679             {
680                 //wl.WriteLogs(ex.ToString());
681             }
682  
683         }
684  
685         /// <summary>
686         /// 更新Excel表格
687         /// </summary>
688         /// <param name="outputFile">需更新的excel表格路径</param>
689         /// <param name="sheetname">sheet名</param>
690         /// <param name="updateData">需更新的数据</param>
691         /// <param name="coluids">需更新的列号</param>
692         /// <param name="rowid">需更新的开始行号</param>
693         public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
694         {
695             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
696  
697             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
698             readfile.Close();
699             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
700             for (int j = 0; j < coluids.Length; j++)
701             {
702                 for (int i = 0; i < updateData[j].Length; i++)
703                 {
704                     try
705                     {
706                         if (sheet1.GetRow(i + rowid) == null)
707                         {
708                             sheet1.CreateRow(i + rowid);
709                         }
710                         if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
711                         {
712                             sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
713                         }
714                         sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
715                     }
716                     catch (Exception ex)
717                     {
718                         //wl.WriteLogs(ex.ToString());
719                     }
720                 }
721             }
722             try
723             {
724                 FileStream writefile = new FileStream(outputFile, FileMode.Create);
725                 hssfworkbook.Write(writefile);
726                 writefile.Close();
727             }
728             catch (Exception ex)
729             {
730                 //wl.WriteLogs(ex.ToString());
731             }
732         }
733  
734         #endregion
735  
736         public static int GetSheetNumber(string outputFile)
737         {
738             int number = 0;
739             try
740             {
741                 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
742  
743                 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
744                 number = hssfworkbook.NumberOfSheets;
745                  
746             }
747             catch (Exception exception)
748             {
749                 //wl.WriteLogs(exception.ToString());
750             }
751             return number;
752         }
753  
754         public static ArrayList GetSheetName(string outputFile)
755         {
756             ArrayList arrayList = new ArrayList();
757             try
758             {
759                 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
760  
761                 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
762                 for(int i = 0 ;i<hssfworkbook.NumberOfSheets;i++)
763                 {
764                     arrayList.Add(hssfworkbook.GetSheetName(i));
765                 }
766             }
767             catch (Exception exception)
768             {
769                 //wl.WriteLogs(exception.ToString());
770             }
771             return arrayList;
772         }
773  
774         public static bool isNumeric(String message, out double result)
775         {
776             Regex rex =new Regex(@"^[-]?d+[.]?d*$");   
777             result = -1;
778             if (rex.IsMatch(message))
779             {
780                 result = double.Parse(message);
781                 return true;
782             }
783             else
784                 return false;
785  
786         }
787     }
788 }
View Code

声明:上面的类是我在网上找来的,功能和写法与下文相似,所以不要对号入座!!!!

公司的高大上的程序员建立代码库,其中有一个功能就是用NPOI导出Excel功能(参考以上的类代码),今天突然有个用户说到他查询出来的数据导出Excel有报错!

调试一番,捕捉到以下错误:

我晕了,高大上的程序员建立的代码库怎么会有错呢?×叉 ×!!完全颠覆我的人生观!!于是问回其作者,得到的答复:”怎么会有错呢?一定是你代码的问题!“

心里犹如万匹草泥马.......很有礼貌地问候了他后,还是一步一步找问题;

经过一番度娘,Stackoverflow后,已经本人亲自操作后发现Excel的列宽

所以导出Excel时列宽超过了255后,就会报错了。

所以应该在Excel列宽上加一层判断:

//设置列宽

if (arrColWidth[column.Ordinal]>255)
{
arrColWidth[column.Ordinal] = 254;
}
else
{
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}

 

总结:为免踩坑,以后引用高大上的类库,也要有怀疑的精神!哎!!

 

posted @ 2016-03-03 15:33  shoupifeng  阅读(6864)  评论(3编辑  收藏  举报