• 导入导出Excel


    最近需要频繁的使用导入导出,各么,又不想使用ms的PIA,在4.0以下,存在版本兼容的问题。

    于是网上查找了很久,找到两款开源的excel组件。

    1、CSharpJExcel,这是JExcel的.net版本,但是只支持到2003,也就是xls格式。

    2、NPOI,这是一款国人写的开源组件,功能挺好,就是代码看着有点乱~尤其是xlsx段。优点在于demo比较详细

    不管如何,先用了再说。

    贴一段改过的helper类

       1 /*******************************************************************
       2  * 版权所有: 
       3  * 类 名 称:ExcelHelper
       4  * 作    者:zk
       5  * 电子邮箱:77148918@QQ.com
       6  * 创建日期:2012/2/25 10:17:21 
       7  * 修改描述:从excel导入datatable时,可以导入日期类型。
       8  *           但对excel中的日期类型有一定要求,要求至少是yyyy/mm/dd类型日期; *           
       9  * 修改描述:将datatable导入excel中,对类型为字符串的数字进行处理,
      10  *           导出数字为double类型;
      11  * 修改描述:针对NPOI 2.0 alpha版本更新,修改了导入excel的方法,划分为2003版本和2007版本;
      12  *           将导入方法里的HSSFWorkbook改为接口;
      13  *           将 NPOI.HSSF.UserModel.HSSFRow改为了NPOI.XSSF.UserModel.XSSFRow(只存在导入excel2007的方法中)
      14  *           将 导入方法的参数HSSFSheet sheet改为了接口类型ISheet(2003的导入方法和2007均有修改) 
      15  *           将 导入方法区分为导入Excel2003以及导入Excel2007;
      16  * 修改日期:2012年5月4日22:06:29 for Jnz Update to NPOI 1.25 正式版
      17  * 修改日期:2012年8月30日17:13:49 for Jnz Update to NPOI 2.0 alpha版
      18  * 修改日期:2015年9月7日  for Feedback Update to NPOI 2.1.3.1 Stable版
      19  * 
      20  * *******************************************************************/
      21 using System;
      22 using System.Collections.Generic;
      23 using System.Data;
      24 using System.IO;
      25 using System.Text;
      26 using System.Web;
      27 using NPOI;
      28 using NPOI.HPSF;
      29 using NPOI.HSSF;
      30 using NPOI.HSSF.Record;//NPOI.HSSF.Record.Formula.Eval改为了NPOI.SS.Formula.Eval;
      31 using NPOI.SS.Formula.Eval;//同上
      32 using NPOI.HSSF.UserModel;
      33 using NPOI.HSSF.Util;
      34 using NPOI.POIFS;
      35 using NPOI.SS.UserModel;
      36 using NPOI.Util;
      37 using NPOI.SS;
      38 using NPOI.DDF;
      39 using NPOI.SS.Util;
      40 using NPOI.XSSF.UserModel;//2007
      41 using System.Collections;
      42 using System.Text.RegularExpressions;
      43 
      44 namespace XX.Carto
      45 {
      46     public class ExcelHelper
      47     {
      48         //private static WriteLog wl = new WriteLog();
      49 
      50 
      51         #region 从datatable中将数据导出到excel
      52         /// <summary>
      53         /// DataTable导出到Excel的MemoryStream
      54         /// </summary>
      55         /// <param name="dtSource">源DataTable</param>
      56         /// <param name="strHeaderText">表头文本</param>
      57         static MemoryStream ExportDT(DataTable dtSource, string strHeaderText)
      58         {
      59             HSSFWorkbook workbook = new HSSFWorkbook();
      60             HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
      61 
      62             #region 右击文件 属性信息
      63 
      64             //{
      65             //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
      66             //    dsi.Company = "http://www.yongfa365.com/";
      67             //    workbook.DocumentSummaryInformation = dsi;
      68 
      69             //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
      70             //    si.Author = "柳永法"; //填加xls文件作者信息
      71             //    si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
      72             //    si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
      73             //    si.Comments = "说明信息"; //填加xls文件作者信息
      74             //    si.Title = "NPOI测试"; //填加xls文件标题信息
      75             //    si.Subject = "NPOI测试Demo"; //填加文件主题信息
      76             //    si.CreateDateTime = DateTime.Now;
      77             //    workbook.SummaryInformation = si;
      78             //}
      79 
      80             #endregion
      81 
      82             HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
      83             HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
      84             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
      85 
      86             //取得列宽
      87             int[] arrColWidth = new int[dtSource.Columns.Count];
      88             foreach (DataColumn item in dtSource.Columns)
      89             {
      90                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
      91             }
      92             for (int i = 0; i < dtSource.Rows.Count; i++)
      93             {
      94                 for (int j = 0; j < dtSource.Columns.Count; j++)
      95                 {
      96                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
      97                     if (intTemp > arrColWidth[j])
      98                     {
      99                         arrColWidth[j] = intTemp;
     100                     }
     101                 }
     102             }
     103             int rowIndex = 0;
     104 
     105             foreach (DataRow row in dtSource.Rows)
     106             {
     107                 #region 新建表,填充表头,填充列头,样式
     108 
     109                 if (rowIndex == 65535 || rowIndex == 0)
     110                 {
     111                     if (rowIndex != 0)
     112                     {
     113                         sheet = workbook.CreateSheet() as HSSFSheet;
     114                     }
     115 
     116                     #region 表头及样式
     117 
     118                     {
     119                         HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
     120                         headerRow.HeightInPoints = 25;
     121                         headerRow.CreateCell(0).SetCellValue(strHeaderText);
     122 
     123                         HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
     124                         headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
     125                         HSSFFont font = workbook.CreateFont() as HSSFFont;
     126                         font.FontHeightInPoints = 20;
     127                         font.Boldweight = 700;
     128                         headStyle.SetFont(font);
     129 
     130                         headerRow.GetCell(0).CellStyle = headStyle;
     131 
     132                         //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));方法已过时
     133                         sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));//2015-09-07 by feedback
     134                         //headerRow.Dispose();
     135                     }
     136 
     137                     #endregion
     138 
     139 
     140                     #region 列头及样式
     141 
     142                     {
     143                         HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
     144 
     145 
     146                         HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
     147                         headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
     148                         HSSFFont font = workbook.CreateFont() as HSSFFont;
     149                         font.FontHeightInPoints = 10;
     150                         font.Boldweight = 700;
     151                         headStyle.SetFont(font);
     152 
     153 
     154                         foreach (DataColumn column in dtSource.Columns)
     155                         {
     156                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
     157                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
     158 
     159                             //设置列宽
     160                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
     161 
     162                         }
     163                         //headerRow.Dispose();
     164                     }
     165 
     166                     #endregion
     167 
     168                     rowIndex = 2;
     169                 }
     170 
     171                 #endregion
     172 
     173                 #region 填充内容
     174 
     175                 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
     176                 foreach (DataColumn column in dtSource.Columns)
     177                 {
     178                     HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
     179 
     180                     string drValue = row[column].ToString();
     181 
     182                     switch (column.DataType.ToString())
     183                     {
     184                         case "System.String": //字符串类型
     185                             double result;
     186                             if (isNumeric(drValue, out result))
     187                             {
     188 
     189                                 double.TryParse(drValue, out result);
     190                                 newCell.SetCellValue(result);
     191                                 break;
     192                             }
     193                             else
     194                             {
     195                                 newCell.SetCellValue(drValue);
     196                                 break;
     197                             }
     198 
     199                         case "System.DateTime": //日期类型
     200                             DateTime dateV;
     201                             DateTime.TryParse(drValue, out dateV);
     202                             newCell.SetCellValue(dateV);
     203 
     204                             newCell.CellStyle = dateStyle; //格式化显示
     205                             break;
     206                         case "System.Boolean": //布尔型
     207                             bool boolV = false;
     208                             bool.TryParse(drValue, out boolV);
     209                             newCell.SetCellValue(boolV);
     210                             break;
     211                         case "System.Int16": //整型
     212                         case "System.Int32":
     213                         case "System.Int64":
     214                         case "System.Byte":
     215                             int intV = 0;
     216                             int.TryParse(drValue, out intV);
     217                             newCell.SetCellValue(intV);
     218                             break;
     219                         case "System.Decimal": //浮点型
     220                         case "System.Double":
     221                             double doubV = 0;
     222                             double.TryParse(drValue, out doubV);
     223                             newCell.SetCellValue(doubV);
     224                             break;
     225                         case "System.DBNull": //空值处理
     226                             newCell.SetCellValue("");
     227                             break;
     228                         default:
     229                             newCell.SetCellValue("");
     230                             break;
     231                     }
     232 
     233                 }
     234 
     235                 #endregion
     236 
     237                 rowIndex++;
     238             }
     239             using (MemoryStream ms = new MemoryStream())
     240             {
     241                 workbook.Write(ms);
     242                 ms.Flush();
     243                 ms.Position = 0;
     244 
     245                 //sheet;
     246                 //workbook.Dispose();
     247 
     248                 return ms;
     249             }
     250         }
     251 
     252         /// <summary>
     253         /// DataTable导出到Excel文件
     254         /// </summary>
     255         /// <param name="dtSource">源DataTable</param>
     256         /// <param name="strHeaderText">表头文本</param>
     257         /// <param name="strFileName">保存位置</param>
     258         public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
     259         {
     260             using (MemoryStream ms = ExportDT(dtSource, strHeaderText))
     261             {
     262                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
     263                 {
     264                     byte[] data = ms.ToArray();
     265                     fs.Write(data, 0, data.Length);
     266                     fs.Flush();
     267                 }
     268             }
     269         }
     270         #endregion
     271 
     272         #region 从excel2003中将数据导出到datatable
     273         /// <summary>读取excel
     274         /// 默认第一行为标头
     275         /// </summary>
     276         /// <param name="strFileName">excel文档路径</param>
     277         /// <returns></returns>
     278         public static DataTable ImportExcel2003toDt(string strFileName)
     279         {
     280             DataTable dt = new DataTable();
     281             IWorkbook hssfworkbook;
     282             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     283             {
     284                 hssfworkbook = new HSSFWorkbook(file);
     285             }
     286             HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
     287             dt = ImportExcel2003InDt(sheet, 0, true);
     288             return dt;
     289         }
     290 
     291         /// <summary>读取excel
     292         /// 默认第一行为标头
     293         /// </summary>
     294         /// <param name="strFileName">excel文档路径</param>
     295         /// <returns></returns>
     296         public static DataTable ImportExcel2007toDt(string strFileName)
     297         {
     298             DataTable dt = new DataTable();
     299             IWorkbook hssfworkbook;
     300             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     301             {
     302                 hssfworkbook = new XSSFWorkbook(file);
     303             }
     304             ISheet sheet = hssfworkbook.GetSheetAt(0);
     305             dt = ImportExcel2007InDt(sheet, 0, true);
     306             return dt;
     307         }
     308 
     309         /// <summary>
     310         /// 读取excel
     311         /// </summary>
     312         /// <param name="strFileName">excel文件路径</param>
     313         /// <param name="sheet">需要导出的sheet</param>
     314         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     315         /// <returns></returns>
     316         public static DataTable ImportExcel2003toDt(string strFileName, string SheetName, int HeaderRowIndex)
     317         {
     318             IWorkbook workbook;
     319             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     320             {
     321                 workbook = new HSSFWorkbook(file);
     322             }
     323             HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
     324             DataTable table = new DataTable();
     325             table = ImportExcel2003InDt(sheet, HeaderRowIndex, true);
     326             //ExcelFileStream.Close();
     327             workbook = null;
     328             sheet = null;
     329             return table;
     330         }
     331 
     332         /// <summary>
     333         /// 读取excel
     334         /// </summary>
     335         /// <param name="strFileName">excel文件路径</param>
     336         /// <param name="sheet">需要导出的sheet</param>
     337         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     338         /// <returns></returns>
     339         public static DataTable ImportExcel2007toDt(string strFileName, string SheetName, int HeaderRowIndex)
     340         {
     341             IWorkbook workbook;
     342             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     343             {
     344                 workbook = new XSSFWorkbook(file);
     345             }
     346             HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
     347             DataTable table = new DataTable();
     348             table = ImportExcel2007InDt(sheet, HeaderRowIndex, true);
     349             //ExcelFileStream.Close();
     350             workbook = null;
     351             sheet = null;
     352             return table;
     353         }
     354 
     355         /// <summary>
     356         /// 读取excel
     357         /// </summary>
     358         /// <param name="strFileName">excel文件路径</param>
     359         /// <param name="sheet">需要导出的sheet序号</param>
     360         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     361         /// <returns></returns>
     362         public static DataTable ImportExcel2003toDt(string strFileName, int SheetIndex, int HeaderRowIndex)
     363         {
     364             HSSFWorkbook workbook;
     365             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     366             {
     367                 workbook = new HSSFWorkbook(file);
     368             }
     369             HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
     370             DataTable table = new DataTable();
     371             table = ImportExcel2003InDt(sheet, HeaderRowIndex, true);
     372             //ExcelFileStream.Close();
     373             workbook = null;
     374             sheet = null;
     375             return table;
     376         }
     377         /// <summary>
     378         /// 读取excel
     379         /// </summary>
     380         /// <param name="strFileName">excel文件路径</param>
     381         /// <param name="sheet">需要导出的sheet序号</param>
     382         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     383         /// <returns></returns>
     384         public static DataTable ImportExcel2007toDt(string strFileName, int SheetIndex, int HeaderRowIndex)
     385         {
     386             IWorkbook workbook;
     387             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     388             {
     389                 workbook = new XSSFWorkbook(file);
     390             }
     391             HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
     392             DataTable table = new DataTable();
     393             table = ImportExcel2007InDt(sheet, HeaderRowIndex, true);
     394             //ExcelFileStream.Close();
     395             workbook = null;
     396             sheet = null;
     397             return table;
     398         }
     399 
     400         /// <summary>
     401         /// 读取excel
     402         /// </summary>
     403         /// <param name="strFileName">excel文件路径</param>
     404         /// <param name="sheet">需要导出的sheet</param>
     405         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     406         /// <returns></returns>
     407         public static DataTable ImportExcel2003toDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader)
     408         {
     409             IWorkbook workbook;
     410             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     411             {
     412                 workbook = new HSSFWorkbook(file);
     413             }
     414             HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
     415             DataTable table = new DataTable();
     416             table = ImportExcel2003InDt(sheet, HeaderRowIndex, needHeader);
     417             //ExcelFileStream.Close();
     418             workbook = null;
     419             sheet = null;
     420             return table;
     421         }
     422 
     423         /// <summary>
     424         /// 读取excel
     425         /// </summary>
     426         /// <param name="strFileName">excel文件路径</param>
     427         /// <param name="sheet">需要导出的sheet序号</param>
     428         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     429         /// <returns></returns>
     430         public static DataTable ImportExcel2003toDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
     431         {
     432             HSSFWorkbook workbook;
     433             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
     434             {
     435                 workbook = new HSSFWorkbook(file);
     436             }
     437             HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
     438             DataTable table = new DataTable();
     439             table = ImportExcel2003InDt(sheet, HeaderRowIndex, needHeader);
     440             //ExcelFileStream.Close();
     441             workbook = null;
     442             sheet = null;
     443             return table;
     444         }
     445 
     446         static DataTable ImportExcel2003InDt(ISheet sheet, int HeaderRowIndex, bool needHeader)
     447         {
     448             DataTable table = new DataTable();
     449             HSSFRow headerRow;
     450             int cellCount;
     451             try
     452             {
     453                 if (HeaderRowIndex < 0 || !needHeader)
     454                 {
     455                     headerRow = sheet.GetRow(0) as HSSFRow;
     456                     cellCount = headerRow.LastCellNum;
     457 
     458                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
     459                     {
     460                         DataColumn column = new DataColumn(Convert.ToString(i));
     461                         table.Columns.Add(column);
     462                     }
     463                 }
     464                 else
     465                 {
     466                     headerRow = sheet.GetRow(HeaderRowIndex) as HSSFRow;
     467                     cellCount = headerRow.LastCellNum;
     468 
     469                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
     470                     {
     471                         if (headerRow.GetCell(i) == null)
     472                         {
     473                             if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
     474                             {
     475                                 DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
     476                                 table.Columns.Add(column);
     477                             }
     478                             else
     479                             {
     480                                 DataColumn column = new DataColumn(Convert.ToString(i));
     481                                 table.Columns.Add(column);
     482                             }
     483 
     484                         }
     485                         else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
     486                         {
     487                             DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
     488                             table.Columns.Add(column);
     489                         }
     490                         else
     491                         {
     492                             DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
     493                             table.Columns.Add(column);
     494                         }
     495                     }
     496                 }
     497                 int rowCount = sheet.LastRowNum;
     498                 for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
     499                 {
     500                     try
     501                     {
     502                         HSSFRow row;
     503                         if (sheet.GetRow(i) == null)
     504                         {
     505                             row = sheet.CreateRow(i) as HSSFRow;
     506                         }
     507                         else
     508                         {
     509                             row = sheet.GetRow(i) as HSSFRow;
     510                         }
     511 
     512                         DataRow dataRow = table.NewRow();
     513 
     514                         for (int j = row.FirstCellNum; j <= cellCount; j++)
     515                         {
     516                             try
     517                             {
     518                                 if (row.GetCell(j) != null)
     519                                 {
     520                                     switch (row.GetCell(j).CellType)
     521                                     {
     522                                         case CellType.String:
     523                                             string str = row.GetCell(j).StringCellValue;
     524                                             if (str != null && str.Length > 0)
     525                                             {
     526                                                 dataRow[j] = str.ToString();
     527                                             }
     528                                             else
     529                                             {
     530                                                 dataRow[j] = null;
     531                                             }
     532                                             break;
     533                                         case CellType.Numeric:
     534                                             if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
     535                                             {
     536                                                 dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
     537                                             }
     538                                             else
     539                                             {
     540                                                 dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
     541                                             }
     542                                             break;
     543                                         case CellType.Boolean:
     544                                             dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
     545                                             break;
     546                                         case CellType.Error:
     547                                             dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
     548                                             break;
     549                                         case CellType.Formula:
     550                                             switch (row.GetCell(j).CachedFormulaResultType)
     551                                             {
     552                                                 case CellType.String:
     553                                                     string strFORMULA = row.GetCell(j).StringCellValue;
     554                                                     if (strFORMULA != null && strFORMULA.Length > 0)
     555                                                     {
     556                                                         dataRow[j] = strFORMULA.ToString();
     557                                                     }
     558                                                     else
     559                                                     {
     560                                                         dataRow[j] = null;
     561                                                     }
     562                                                     break;
     563                                                 case CellType.Numeric:
     564                                                     dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
     565                                                     break;
     566                                                 case CellType.Boolean:
     567                                                     dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
     568                                                     break;
     569                                                 case CellType.Error:
     570                                                     dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
     571                                                     break;
     572                                                 default:
     573                                                     dataRow[j] = "";
     574                                                     break;
     575                                             }
     576                                             break;
     577                                         default:
     578                                             dataRow[j] = "";
     579                                             break;
     580                                     }
     581                                 }
     582                             }
     583                             catch (Exception exception)
     584                             {
     585                                 //wl.WriteLogs(exception.ToString());
     586                             }
     587                         }
     588                         table.Rows.Add(dataRow);
     589                     }
     590                     catch (Exception exception)
     591                     {
     592                         //wl.WriteLogs(exception.ToString());
     593                     }
     594                 }
     595             }
     596             catch (Exception exception)
     597             {
     598                 //wl.WriteLogs(exception.ToString());
     599             }
     600             return table;
     601         }
     602 
     603         /// <summary>
     604         /// 将制定sheet中的数据导出到datatable中
     605         /// </summary>
     606         /// <param name="sheet">需要导出的sheet</param>
     607         /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
     608         /// <returns></returns>
     609         static DataTable ImportExcel2007InDt(ISheet sheet, int HeaderRowIndex, bool needHeader)
     610         {
     611             DataTable table = new DataTable();
     612             NPOI.XSSF.UserModel.XSSFRow headerRow;
     613             int cellCount;
     614             try
     615             {
     616                 if (HeaderRowIndex < 0 || !needHeader)
     617                 {
     618                     headerRow = sheet.GetRow(0) as NPOI.XSSF.UserModel.XSSFRow;
     619                     cellCount = headerRow.LastCellNum;
     620 
     621                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
     622                     {
     623                         DataColumn column = new DataColumn(Convert.ToString(i));
     624                         table.Columns.Add(column);
     625                     }
     626                 }
     627                 else
     628                 {
     629                     headerRow = sheet.GetRow(HeaderRowIndex) as NPOI.XSSF.UserModel.XSSFRow;
     630                     cellCount = headerRow.LastCellNum;
     631 
     632                     for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
     633                     {
     634                         if (headerRow.GetCell(i) == null)
     635                         {
     636                             if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
     637                             {
     638                                 DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
     639                                 table.Columns.Add(column);
     640                             }
     641                             else
     642                             {
     643                                 DataColumn column = new DataColumn(Convert.ToString(i));
     644                                 table.Columns.Add(column);
     645                             }
     646 
     647                         }
     648                         else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
     649                         {
     650                             DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
     651                             table.Columns.Add(column);
     652                         }
     653                         else
     654                         {
     655                             DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
     656                             table.Columns.Add(column);
     657                         }
     658                     }
     659                 }
     660                 int rowCount = sheet.LastRowNum;
     661                 for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
     662                 {
     663                     try
     664                     {
     665                         NPOI.XSSF.UserModel.XSSFRow row;
     666                         if (sheet.GetRow(i) == null)
     667                         {
     668                             row = sheet.CreateRow(i) as NPOI.XSSF.UserModel.XSSFRow;
     669                         }
     670                         else
     671                         {
     672                             row = sheet.GetRow(i) as NPOI.XSSF.UserModel.XSSFRow;
     673                         }
     674 
     675                         DataRow dataRow = table.NewRow();
     676 
     677                         for (int j = row.FirstCellNum; j <= cellCount; j++)
     678                         {
     679                             try
     680                             {
     681                                 if (row.GetCell(j) != null)
     682                                 {
     683                                     switch (row.GetCell(j).CellType)
     684                                     {
     685                                         case CellType.String:
     686                                             string str = row.GetCell(j).StringCellValue;
     687                                             if (str != null && str.Length > 0)
     688                                             {
     689                                                 dataRow[j] = str.ToString();
     690                                             }
     691                                             else
     692                                             {
     693                                                 dataRow[j] = null;
     694                                             }
     695                                             break;
     696                                         case CellType.Numeric:
     697                                             if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
     698                                             {
     699                                                 dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
     700                                             }
     701                                             else
     702                                             {
     703                                                 dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
     704                                             }
     705                                             break;
     706                                         case CellType.Boolean:
     707                                             dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
     708                                             break;
     709                                         case CellType.Error:
     710                                             dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
     711                                             break;
     712                                         case CellType.Formula:
     713                                             switch (row.GetCell(j).CachedFormulaResultType)
     714                                             {
     715                                                 case CellType.String:
     716                                                     string strFORMULA = row.GetCell(j).StringCellValue;
     717                                                     if (strFORMULA != null && strFORMULA.Length > 0)
     718                                                     {
     719                                                         dataRow[j] = strFORMULA.ToString();
     720                                                     }
     721                                                     else
     722                                                     {
     723                                                         dataRow[j] = null;
     724                                                     }
     725                                                     break;
     726                                                 case CellType.Numeric:
     727                                                     dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
     728                                                     break;
     729                                                 case CellType.Boolean:
     730                                                     dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
     731                                                     break;
     732                                                 case CellType.Error:
     733                                                     dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
     734                                                     break;
     735                                                 default:
     736                                                     dataRow[j] = "";
     737                                                     break;
     738                                             }
     739                                             break;
     740                                         default:
     741                                             dataRow[j] = "";
     742                                             break;
     743                                     }
     744                                 }
     745                             }
     746                             catch (Exception exception)
     747                             {
     748                                 //wl.WriteLogs(exception.ToString());
     749                             }
     750                         }
     751                         table.Rows.Add(dataRow);
     752                     }
     753                     catch (Exception exception)
     754                     {
     755                         //wl.WriteLogs(exception.ToString());
     756                     }
     757                 }
     758             }
     759             catch (Exception exception)
     760             {
     761                 //wl.WriteLogs(exception.ToString());
     762             }
     763             return table;
     764         }
     765         #endregion
     766 
     767         #region 更新excel中的数据
     768 
     769         //批量更新,必须所有的excel都是一样的格式
     770         public static void UpdateExcelBatch(string outputFile, List<DataTable> pListTable)
     771         {
     772             //列从0开始
     773             //行从0开始
     774             int coluid = 0;
     775             int rowid = 1;
     776 
     777             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
     778 
     779             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
     780 
     781             foreach (DataTable pTable in pListTable)
     782             {
     783                 string sheetname = pTable.TableName;//对应excel的sheet
     784                 ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
     785                 int rownum = 1;
     786                 int column = 0;
     787                 foreach (DataRow pRow in pTable.Rows)
     788                 {
     789                     try
     790                     {
     791                         IRow pR = sheet1.CreateRow(rownum);
     792                         for (int k = 0; k < pTable.Columns.Count; k++)
     793                         {
     794                             column = k + coluid;//列从0开始
     795                             ICell pCell = pR.CreateCell(column);
     796                             pCell.SetCellValue(pRow[k].ToString());
     797                         }
     798                         rownum++;
     799                         //  column++;
     800                     }
     801                     catch (Exception ex)
     802                     {
     803                         // wl.WriteLogs(ex.ToString());
     804                         throw;
     805                     }
     806                 }
     807             }
     808             try
     809             {
     810                 readfile.Close();
     811                 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
     812                 hssfworkbook.Write(writefile);
     813                 writefile.Close();
     814             }
     815             catch (Exception ex)
     816             {
     817                 // wl.WriteLogs(ex.ToString());
     818             }
     819 
     820         }
     821 
     822         public static void UpdateExcel(string outputFile, string sheetname, DataTable pTable)
     823         {
     824             //列从0开始
     825             //行从0开始
     826             int coluid = 0;
     827             int rowid = 1;
     828 
     829             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
     830 
     831             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
     832             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
     833             int rownum = 1;
     834             int column = 0;
     835             foreach (DataRow pRow in pTable.Rows)
     836             {
     837                 try
     838                 {
     839                     IRow pR = sheet1.CreateRow(rownum);
     840                     for (int k = 0; k < pTable.Columns.Count; k++)
     841                     {
     842                         column = k + coluid;//列从0开始
     843                         ICell pCell = pR.CreateCell(column);
     844                         pCell.SetCellValue(pRow[k].ToString());
     845                     }
     846                     rownum++;
     847                     //  column++;
     848                 }
     849                 catch (Exception ex)
     850                 {
     851                     // wl.WriteLogs(ex.ToString());
     852                     throw;
     853                 }
     854             }
     855             try
     856             {
     857                 readfile.Close();
     858                 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
     859                 hssfworkbook.Write(writefile);
     860                 writefile.Close();
     861             }
     862             catch (Exception ex)
     863             {
     864                 // wl.WriteLogs(ex.ToString());
     865             }
     866 
     867         }
     868         /// <summary>
     869         /// 更新Excel表格
     870         /// </summary>
     871         /// <param name="outputFile">需更新的excel表格路径</param>
     872         /// <param name="sheetname">sheet名</param>
     873         /// <param name="updateData">需更新的数据</param>
     874         /// <param name="coluid">需更新的列号</param>
     875         /// <param name="rowid">需更新的开始行号</param>
     876         public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid)
     877         {
     878             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
     879 
     880             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
     881             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
     882             for (int i = 0; i < updateData.Length; i++)
     883             {
     884                 try
     885                 {
     886                     if (sheet1.GetRow(i + rowid) == null)
     887                     {
     888                         sheet1.CreateRow(i + rowid);
     889                     }
     890                     if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
     891                     {
     892                         sheet1.GetRow(i + rowid).CreateCell(coluid);
     893                     }
     894 
     895                     sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
     896                 }
     897                 catch (Exception ex)
     898                 {
     899                     // wl.WriteLogs(ex.ToString());
     900                     throw;
     901                 }
     902             }
     903             try
     904             {
     905                 readfile.Close();
     906                 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
     907                 hssfworkbook.Write(writefile);
     908                 writefile.Close();
     909             }
     910             catch (Exception ex)
     911             {
     912                 // wl.WriteLogs(ex.ToString());
     913             }
     914 
     915         }
     916 
     917         /// <summary>
     918         /// 更新Excel表格
     919         /// </summary>
     920         /// <param name="outputFile">需更新的excel表格路径</param>
     921         /// <param name="sheetname">sheet名</param>
     922         /// <param name="updateData">需更新的数据</param>
     923         /// <param name="coluids">需更新的列号</param>
     924         /// <param name="rowid">需更新的开始行号</param>
     925         public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid)
     926         {
     927             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
     928 
     929             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
     930             readfile.Close();
     931             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
     932             for (int j = 0; j < coluids.Length; j++)
     933             {
     934                 for (int i = 0; i < updateData[j].Length; i++)
     935                 {
     936                     try
     937                     {
     938                         if (sheet1.GetRow(i + rowid) == null)
     939                         {
     940                             sheet1.CreateRow(i + rowid);
     941                         }
     942                         if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
     943                         {
     944                             sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
     945                         }
     946                         sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
     947                     }
     948                     catch (Exception ex)
     949                     {
     950                         // wl.WriteLogs(ex.ToString());
     951                     }
     952                 }
     953             }
     954             try
     955             {
     956                 FileStream writefile = new FileStream(outputFile, FileMode.Create);
     957                 hssfworkbook.Write(writefile);
     958                 writefile.Close();
     959             }
     960             catch (Exception ex)
     961             {
     962                 //wl.WriteLogs(ex.ToString());
     963             }
     964         }
     965 
     966         /// <summary>
     967         /// 更新Excel表格
     968         /// </summary>
     969         /// <param name="outputFile">需更新的excel表格路径</param>
     970         /// <param name="sheetname">sheet名</param>
     971         /// <param name="updateData">需更新的数据</param>
     972         /// <param name="coluid">需更新的列号</param>
     973         /// <param name="rowid">需更新的开始行号</param>
     974         public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
     975         {
     976             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
     977 
     978             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
     979             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
     980             for (int i = 0; i < updateData.Length; i++)
     981             {
     982                 try
     983                 {
     984                     if (sheet1.GetRow(i + rowid) == null)
     985                     {
     986                         sheet1.CreateRow(i + rowid);
     987                     }
     988                     if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
     989                     {
     990                         sheet1.GetRow(i + rowid).CreateCell(coluid);
     991                     }
     992 
     993                     sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
     994                 }
     995                 catch (Exception ex)
     996                 {
     997                     //wl.WriteLogs(ex.ToString());
     998                     throw;
     999                 }
    1000             }
    1001             try
    1002             {
    1003                 readfile.Close();
    1004                 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
    1005                 hssfworkbook.Write(writefile);
    1006                 writefile.Close();
    1007             }
    1008             catch (Exception ex)
    1009             {
    1010                 //wl.WriteLogs(ex.ToString());
    1011             }
    1012 
    1013         }
    1014 
    1015         /// <summary>
    1016         /// 更新Excel表格
    1017         /// </summary>
    1018         /// <param name="outputFile">需更新的excel表格路径</param>
    1019         /// <param name="sheetname">sheet名</param>
    1020         /// <param name="updateData">需更新的数据</param>
    1021         /// <param name="coluids">需更新的列号</param>
    1022         /// <param name="rowid">需更新的开始行号</param>
    1023         public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
    1024         {
    1025             FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    1026 
    1027             HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    1028             readfile.Close();
    1029             ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
    1030             for (int j = 0; j < coluids.Length; j++)
    1031             {
    1032                 for (int i = 0; i < updateData[j].Length; i++)
    1033                 {
    1034                     try
    1035                     {
    1036                         if (sheet1.GetRow(i + rowid) == null)
    1037                         {
    1038                             sheet1.CreateRow(i + rowid);
    1039                         }
    1040                         if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
    1041                         {
    1042                             sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
    1043                         }
    1044                         sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
    1045                     }
    1046                     catch (Exception ex)
    1047                     {
    1048                         //wl.WriteLogs(ex.ToString());
    1049                     }
    1050                 }
    1051             }
    1052             try
    1053             {
    1054                 FileStream writefile = new FileStream(outputFile, FileMode.Create);
    1055                 hssfworkbook.Write(writefile);
    1056                 writefile.Close();
    1057             }
    1058             catch (Exception ex)
    1059             {
    1060                 //wl.WriteLogs(ex.ToString());
    1061             }
    1062         }
    1063 
    1064         #endregion
    1065 
    1066         public static int GetSheetNumber(string outputFile)
    1067         {
    1068             int number = 0;
    1069             try
    1070             {
    1071                 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    1072 
    1073                 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    1074                 number = hssfworkbook.NumberOfSheets;
    1075 
    1076             }
    1077             catch (Exception exception)
    1078             {
    1079                 //wl.WriteLogs(exception.ToString());
    1080             }
    1081             return number;
    1082         }
    1083 
    1084         public static List<string> GetSheetName(string outputFile)
    1085         {
    1086             List<string> arrayList = new List<string>();
    1087             try
    1088             {
    1089                 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
    1090 
    1091                 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
    1092                 for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
    1093                 {
    1094                     arrayList.Add(hssfworkbook.GetSheetName(i));
    1095                 }
    1096             }
    1097             catch (Exception exception)
    1098             {
    1099                 //wl.WriteLogs(exception.ToString());
    1100             }
    1101             return arrayList;
    1102         }
    1103 
    1104         public static bool isNumeric(String message, out double result)
    1105         {
    1106             Regex rex = new Regex(@"^[-]?d+[.]?d*$");
    1107             result = -1;
    1108             if (rex.IsMatch(message))
    1109             {
    1110                 result = double.Parse(message);
    1111                 return true;
    1112             }
    1113             else
    1114                 return false;
    1115 
    1116         }
    1117     }
    1118 }
    View Code
  • 相关阅读:
    [Redis]主从同步可能遇到的坑
    Redis_如何保证原子操作
    .Net Core 5.0 Json序列化和反序列化 | System.Text.Json 的json序列化和反序列化
    JavaScript Error对象整理_JavaScript 异常处理整理
    Canvas 事件绑定|Canvas事件处理
    Css3 常用布局方式 一行两列&高度自适应&垂直方向居中
    Css3 实现锯齿效果整理
    Css3 currentColor 变量使用
    Css3 实现任意角扇形|Css3实现六角扇形
    实现 Application_Start 和 Application_End
  • 原文地址:https://www.cnblogs.com/feedback/p/4790839.html
Copyright © 2020-2023  润新知