NPOI导出数据到Excel

本文介绍了如何使用NPOI库将数据导出到Excel文件,提供了NPOI的下载链接,并指出了解决NPOI不支持Excel2007问题的方法——使用Excel2003模板。此外,还提及导出过程需要一个预先准备的Excel模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前阵子工作需要,将数据库数据导出到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;
                }
            }

导出成功!而且速度很快 微笑



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值