NPOI导出数据到Excel

时间:2021-11-27 14:45:14
前阵子工作需要,将数据库数据导出到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模板。

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

string tempPath = "";
//设置Excel模板的存放路径
tempPath = Server.MapPath("~/xls_files/Template_DeviceIP.xls");
if (tempPath.Length > 0)
{
string sql = "select ip,ipUser,state,dept from ip_info ";
// 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";
// DataTable dtcomm = DbHelperSQL.Query(sql1).Tables[0];
DataTable dtsoc = DbHelperSQL.Query(sql).Tables[0];
if (dtsoc != null && dtsoc.Rows.Count > 0)
{

FileStream file = new FileStream(tempPath, FileMode.Open, FileAccess.Read);//读入excel模板
IWorkbook workbook = new HSSFWorkbook(file);
//设置Excel的样式,这里设置了表格的边框和高度
ICellStyle datastyle = workbook.CreateCellStyle();
datastyle.Alignment = HorizontalAlignment.Center;
datastyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
datastyle.TopBorderColor = HSSFColor.Black.Index;
datastyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
datastyle.RightBorderColor = HSSFColor.Black.Index;
datastyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
datastyle.BottomBorderColor = HSSFColor.Black.Index;
datastyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
datastyle.LeftBorderColor = HSSFColor.Black.Index;
IFont datafont = workbook.CreateFont();
datafont.FontHeightInPoints = 10;//字号
datastyle.SetFont(datafont);


string bakPath = "IP表.xls";
int totalIndex = dtsoc.Rows.Count;
int rowIndex = 3; // 起始行
int dtRowIndex = dtsoc.Rows.Count; // DataTable的数据行数

ISheet sheet = workbook.GetSheet("IP表");
foreach (DataRow row in dtsoc.Rows)
{
#region 填充内容
//HSSFRow dataRow = sheet.GetRow(rowIndex);
IRow dataRow = sheet.CreateRow(rowIndex);
int columnIndex = 0; // 开始列(0为标题列,从1开始)
foreach (DataColumn column in dtsoc.Columns)
{
// 列序号赋值
if (columnIndex >= dtsoc.Columns.Count)
break;

//HSSFCell newCell = dataRow.GetCell(columnIndex);
//if (newCell == null)
ICell newCell = dataRow.CreateCell(columnIndex);
string drValue = row[column].ToString();


switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
newCell.CellStyle = datastyle;
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = datastyle;
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
newCell.CellStyle = datastyle;
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
newCell.CellStyle = datastyle;
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
newCell.CellStyle = datastyle;
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
newCell.CellStyle = datastyle;
break;
default:
newCell.SetCellValue("");
newCell.CellStyle = datastyle;
break;
}
columnIndex++;
}
#endregion

rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
workbook = null;


//sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
byte[] data = ms.ToArray();
//fs.Write(data, 0, data.Length);

#region 客户端保存
HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
//Encoding pageEncode = Encoding.GetEncoding(PageEncode);
response.Charset = "UTF-8";
response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + bakPath));
System.Web.HttpContext.Current.Response.BinaryWrite(data);
}

}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert('无数据导出!');", true);
return;
}
}

导出成功!而且速度很快 NPOI导出数据到Excel

NPOI导出数据到Excel