NPOI导出数据到Excel

前阵子工作需要,将数据库数据导出到Excel。试了很多方法包括excelpackage(见上一篇),最后还是感觉NPOI比较好用一些。事实证明NPOI使用很简洁,在.net项目中只需引入一个NPOI.dll文件即可。

官网下载地址:http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=npoi&DownloadId=764162&FileTime=130334008104200000&Build=20885

(是不是很简洁)

 

然后就是代码了,这里我导出的是一个标准Excel格式。对于同学们算是一个入门级教程,同学们若想了解更多NPOI 可以自己慢慢研究~ 另外,我这里导出需要提供一个Excel模板,放到指定的目录中。

对于NPOI不支持Excel2007的问题(我本机是Excel2007),我的解决办法是:放了一个Excel2003的Excel模板。

下面附上我的导出方法代码:

 

  1  string tempPath =  "";
  2              // 设置Excel模板的存放路径
  3              tempPath = Server.MapPath( " ~/xls_files/Template_DeviceIP.xls ");
  4              if (tempPath.Length >  0)
  5             {
  6                  string sql =  " select ip,ipUser,state,dept from ip_info  ";
  7                  //   string sql1 = "select orderId,range,comm_soc_orgname,distinguish,classes,createtime,competent_name,prin_name,phonenumber,numbercount,isParty from st_comm_soc_org order by orderId";
  8                   //  DataTable dtcomm = DbHelperSQL.Query(sql1).Tables[0];
  9                  DataTable dtsoc = DbHelperSQL.Query(sql).Tables[ 0];
 10                  if (dtsoc !=  null && dtsoc.Rows.Count >  0)
 11                 {
 12 
 13                     FileStream file =  new FileStream(tempPath, FileMode.Open, FileAccess.Read); // 读入excel模板
 14                      IWorkbook workbook =  new HSSFWorkbook(file);
 15                      // 设置Excel的样式,这里设置了表格的边框和高度
 16                      ICellStyle datastyle = workbook.CreateCellStyle();
 17                     datastyle.Alignment = HorizontalAlignment.Center;
 18                     datastyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
 19                     datastyle.TopBorderColor = HSSFColor.Black.Index;
 20                     datastyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
 21                     datastyle.RightBorderColor = HSSFColor.Black.Index;
 22                     datastyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
 23                     datastyle.BottomBorderColor = HSSFColor.Black.Index;
 24                     datastyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
 25                     datastyle.LeftBorderColor = HSSFColor.Black.Index;
 26                     IFont datafont = workbook.CreateFont();
 27                     datafont.FontHeightInPoints =  10; // 字号
 28                      datastyle.SetFont(datafont);
 29 
 30 
 31                      string bakPath =  " IP表.xls ";
 32                      int totalIndex = dtsoc.Rows.Count;
 33                      int rowIndex =  3;        //  起始行
 34                       int dtRowIndex = dtsoc.Rows.Count;        //  DataTable的数据行数
 35 
 36                     ISheet sheet = workbook.GetSheet( " IP表 ");
 37                      foreach (DataRow row  in dtsoc.Rows)
 38                     {
 39                          #region 填充内容
 40                          // HSSFRow dataRow = sheet.GetRow(rowIndex);
 41                          IRow dataRow = sheet.CreateRow(rowIndex);
 42                          int columnIndex =  0;         //  开始列(0为标题列,从1开始)
 43                           foreach (DataColumn column  in dtsoc.Columns)
 44                         {
 45                              //  列序号赋值
 46                               if (columnIndex >= dtsoc.Columns.Count)
 47                                  break;
 48 
 49                              // HSSFCell newCell = dataRow.GetCell(columnIndex);
 50                               // if (newCell == null)
 51                              ICell newCell = dataRow.CreateCell(columnIndex);
 52                              string drValue = row[column].ToString();
 53 
 54 
 55                              switch (column.DataType.ToString())
 56                             {
 57                                  case  " System.String ": // 字符串类型
 58                                      newCell.SetCellValue(drValue);
 59                                     newCell.CellStyle = datastyle;
 60                                      break;
 61                                  case  " System.DateTime ": // 日期类型
 62                                      DateTime dateV;
 63                                     DateTime.TryParse(drValue,  out dateV);
 64                                     newCell.SetCellValue(dateV);
 65                                     newCell.CellStyle = datastyle;
 66                                      break;
 67                                  case  " System.Boolean ": // 布尔型
 68                                       bool boolV =  false;
 69                                      bool.TryParse(drValue,  out boolV);
 70                                     newCell.SetCellValue(boolV);
 71                                     newCell.CellStyle = datastyle;
 72                                      break;
 73                                  case  " System.Int16 ": // 整型
 74                                   case  " System.Int32 ":
 75                                  case  " System.Int64 ":
 76                                  case  " System.Byte ":
 77                                      int intV =  0;
 78                                      int.TryParse(drValue,  out intV);
 79                                     newCell.SetCellValue(intV);
 80                                     newCell.CellStyle = datastyle;
 81                                      break;
 82                                  case  " System.Decimal ": // 浮点型
 83                                   case  " System.Double ":
 84                                      double doubV =  0;
 85                                      double.TryParse(drValue,  out doubV);
 86                                     newCell.SetCellValue(doubV);
 87                                     newCell.CellStyle = datastyle;
 88                                      break;
 89                                  case  " System.DBNull ": // 空值处理
 90                                      newCell.SetCellValue( "");
 91                                     newCell.CellStyle = datastyle;
 92                                      break;
 93                                  default:
 94                                     newCell.SetCellValue( "");
 95                                     newCell.CellStyle = datastyle;
 96                                      break;
 97                             }
 98                             columnIndex++;
 99                         }
100                          #endregion
101 
102                         rowIndex++;
103                     }
104                      using (MemoryStream ms =  new MemoryStream())
105                     {
106                         workbook.Write(ms);
107                         ms.Flush();
108                         ms.Position =  0;
109                         sheet =  null;
110                         workbook =  null;
111 
112 
113                          // sheet.Dispose();
114                           // workbook.Dispose(); // 一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
115                           byte[] data = ms.ToArray();
116                          // fs.Write(data, 0, data.Length);
117 
118                          #region 客户端保存
119                         HttpResponse response = System.Web.HttpContext.Current.Response;
120                         response.Clear();
121                          // Encoding pageEncode = Encoding.GetEncoding(PageEncode);
122                          response.Charset =  " UTF-8 ";
123                         response.ContentType =  " application/vnd-excel "; // "application/vnd.ms-excel";
124                          System.Web.HttpContext.Current.Response.AddHeader( " Content-Disposition "string.Format( " attachment; filename= " + bakPath));
125                         System.Web.HttpContext.Current.Response.BinaryWrite(data);
126                     }
127 
128                 }
129                  else
130                 {
131                     Page.ClientScript.RegisterStartupScript( this.GetType(),  " ClientScript "" alert('无数据导出!'); "true);
132                      return;
133                 }
134             }
View Code

 

导出成功!而且速度很快 

 

 

你可能感兴趣的:(Excel)