NOPI导入导出EXCEL

时间:2022-09-24 14:37:49

一、简介

1. 什么是NPOI

NPOI,顾名思义,就是POI的.NET版本。那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。在本文发布时,POI的最新版本是3.5 beta 6。

NPOI 1.x是基于POI 3.x版本开发的,与poi 3.2对应的版本是NPOI 1.2,目前最新发布的版本是1.2.1,在该版本中仅支持读写Excel文件和Drawing格式,其他文件格式将在以后的版本中得到支持。

1.2  目前POI版本中的HWPF(用于Word的读写库)还不是很稳定,并非正式发布版本,且负责HWPF的关键开发人员已经离开,所以NPOI可能考虑自己重新开发HWPF。另外,目前微软正在开发Open XML Format SDK,NPOI可能会放弃对ooxml的支持,当然这取决于用户的需求和Open XML Format SDK的稳定性和速度。从目前而言,NPOI有几大优势

第一,完全基于.NET 2.0,而非.NET 3.0/3.5。

第二,读写速度快(有个国外的兄弟回复说,他原来用ExcelPackage生成用了4-5个小时,现在只需要4-5分钟)

第三,稳定性好(相对于用Office OIA而言,毕竟那东西是基于Automation做的,在Server上跑个Automation的东西,想想都觉得可怕),跑过了将近1000个测试用例(来自于POI的testcase目录)

第四,API简单易用,当然这得感谢POI的设计师们

第五,完美支持Excel 2003格式(据说myxls无法正确读取xls模板,但NPOI可以),以后也许是所有Office 2003格式

希望NPOI把这些优势继续发扬下去,这样NPOI才会更有竞争力。

1.3  NPOI 1.2中各Assembly的作用

NPOI目前有好几个assembly,每个的作用各有不同,开发人员可以按需加载相应的assembly。在这里大概罗列一下:

NPOI.Util  基础辅助库
NPOI.POIFS   OLE2格式读写库
NPOI.DDF   Microsoft Drawing格式读写库
NPOI.SS   Excel公式计算库
NPOI.HPSF   OLE2的Summary Information和Document Summary Information属性读写库
NPOI.HSSF   Excel BIFF格式读写库

 

 ps:先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中添加引用。

 

二、导入EXCEL

 #region==Excel导入==
        
        private void ExcelImport()
        {
            
            string fileurl = GetFormString("fileurl");
            if (fileurl != "")
            {
                string FileName = HttpRuntime.AppDomainAppPath.ToString() + fileurl;
                FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                IWorkbook book = null;  //新建IWorkbook对象  

                if (FileName.IndexOf(".xlsx") > 0) // 2007版本  
                {
                    book = new XSSFWorkbook(fs);  //xlsx数据读入workbook  
                }
                else if (FileName.IndexOf(".xls") > 0) // 2003版本  
                {
                    book = new HSSFWorkbook(fs);  //xls数据读入workbook  
                }
                //待收货订单
                BLL.t_order bll = new BLL.t_order();
                List<Model.t_order> listorder = bll.GetModelList(" OrderState=2  ");
                List<string> strlist = new List<string>();

                int sheetCount = book.NumberOfSheets;
                for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++)
                {
                    NPOI.SS.UserModel.ISheet sheet = book.GetSheetAt(sheetIndex);//获取第sheetIndex个工作表  
                    if (sheet == null) continue;

                    NPOI.SS.UserModel.IRow row = sheet.GetRow(0);
                    if (row == null) continue;
                    int firstCellNum = row.FirstCellNum;
                    int lastCellNum = row.LastCellNum;
                    if (firstCellNum == lastCellNum) continue;

                    for (int i = 1; i <= sheet.LastRowNum; i++)//对工作表除去表头的每一行
                    {
                        string cellValue = "";
                        for (int j = firstCellNum; j < lastCellNum; j++)
                        {
                            cellValue += sheet.GetRow(i).GetCell(j).ToString() + ",";//将每一行的数据以,相连
                        }
                        strlist.Add(cellValue);
                    }
                }
            
                for (int j = 0; j < strlist.Count; j++)
                {
                    if (strlist[j] != "")
                    {
                      string[] arr = strlist[j].Split(',');   //再进行拆分
                        for (int k = 0; k < listorder.Count; k++)
                        {

                            if (listorder[k].BillNumber == arr[0])
                            {
                                listorder[k].FreightNumber = arr[1];
                                listorder[k].FreightName = arr[2];
                                bll.Update(listorder[k]);
                                break;
                            }
                        }
                    }
                }
                fs.Close();
                //book.Close();  
                Common.Utils.DeleteUpFile(fileurl);
                ResponseText(Newtonsoft.Json.JsonConvert.SerializeObject(new { res = 1, msg = "操作成功!" }));
            }
            else {
                ResponseText(Newtonsoft.Json.JsonConvert.SerializeObject(new { res = 0, msg = "操作失败!" }));
            
            }                
        }
        #endregion

 

三、导出EXCEL

   #region==导出订单==
        private HSSFWorkbook BuildSwitchData(List<Model.t_order> lS)
        {
           
          
            try
            {
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = (HSSFSheet)wb.CreateSheet("待发货订单"); //创建工作表
                sheet.CreateFreezePane(0, 1); //冻结列头行
                HSSFRow row_Title = (HSSFRow)sheet.CreateRow(0); //创建列头行
                row_Title.HeightInPoints = 19.5F; //设置列头行高

                #region 设置列宽
                sheet.SetColumnWidth(0, 50 * 256);
                sheet.SetColumnWidth(1, 24 * 256);
                sheet.SetColumnWidth(2, 37 * 256);
                sheet.SetColumnWidth(3, 22 * 256);
                sheet.SetColumnWidth(4, 20 * 256);
                sheet.SetColumnWidth(5, 20 * 256);
                #endregion

                #region 设置列头单元格样式
                HSSFCellStyle cs_Title = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
                cs_Title.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
                cs_Title.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
                HSSFFont cs_Title_Font = (HSSFFont)wb.CreateFont(); //创建字体
                cs_Title_Font.Boldweight = 700; //字体加粗
                cs_Title_Font.FontHeightInPoints = 12; //字体大小
                cs_Title.SetFont(cs_Title_Font); //将字体绑定到样式
                #endregion

                #region 生成列头
                for (int i = 0; i < 8; i++)
                {
                    HSSFCell cell_Title = (HSSFCell)row_Title.CreateCell(i); //创建单元格
                    cell_Title.CellStyle = cs_Title; //将样式绑定到单元格
                    switch (i)
                    {
                        case 0:
                            cell_Title.SetCellValue("订单编号");
                            break;
                        case 1:
                            cell_Title.SetCellValue("商品信息");
                            break;
                        case 2:
                            cell_Title.SetCellValue("收件人姓名");
                            break;
                        case 3:
                            cell_Title.SetCellValue("收件人电话");
                            break;
                        case 4:
                            cell_Title.SetCellValue("收件人地址");
                            break;
                        case 5:
                            cell_Title.SetCellValue("寄件人姓名");
                            break;
                        case 6:
                            cell_Title.SetCellValue("寄件人电话");
                            break;
                        case 7:
                            cell_Title.SetCellValue("寄件人地址");
                            break;
                    }
                }
                #endregion

                for (int i = 0; i < lS.Count; i++)
                {
                    #region 设置内容单元格样式
                    HSSFCellStyle cs_Content = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
                    cs_Content.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
                    cs_Content.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
                    #endregion

                    #region 生成内容单元格
                    HSSFRow row_Content = (HSSFRow)sheet.CreateRow(i + 1); //创建行
                    row_Content.HeightInPoints = 16;
                    for (int j = 0; j < 8; j++)
                    {
                        HSSFCell cell_Conent = (HSSFCell)row_Content.CreateCell(j); //创建单元格
                        cell_Conent.CellStyle = cs_Content;
                        switch (j)
                        {
                            case 0:
                                cell_Conent.SetCellValue(lS[i].BillNumber);
                                break;
                            case 1:
                                cell_Conent.SetCellValue(OrderGoodsInfo(lS[i].ID.ToString()));
                                break;
                            case 2:
                                cell_Conent.SetCellValue(lS[i].ContactPeople);
                                break;
                            case 3:
                                cell_Conent.SetCellValue(lS[i].ContactPhone);
                                break;
                            case 4:
                                cell_Conent.SetCellValue(lS[i].AddrDesc);
                                break;
                            case 5:
                                cell_Conent.SetCellValue(lS[i].DeliverPeople);
                                break;
                            case 6:
                                cell_Conent.SetCellValue(lS[i].DeliverPhone);
                                break;
                            case 7:
                                cell_Conent.SetCellValue("");
                                break;
                        }
                    }
                    #endregion
                }

                return wb;
            }
            catch { return null; }

        }
        //获得订单商品信息
        private string OrderGoodsInfo(string orderid) {
            string info = "";
            List<Model.t_orderdetail> list = new BLL.t_orderdetail().GetModelList(" OrderID ='" + orderid + "'");
            for (int i = 0; i < list.Count; i++) {
                info += "【" + list[i].GoodsName + " 规格:" + list[i].SpecDesc + " 数量:" + list[i].GoodsCount+ "】";
            }
              return info;
        
        }

        protected void fileBtn2_Click(object sender, EventArgs e)
        {
            try
            {
                List<Model.t_order> lS = new List<Model.t_order>();
                BLL.t_order bll = new BLL.t_order();
                Model.t_order order = null;
                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    string id = ((HiddenField)rptList.Items[i].FindControl("hidId")).Value;
                    CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                    if (cb.Checked)
                    {
                        order = bll.GetModel(Common.Utils.ToGuid(id));
                        if (order != null)
                        {
                            lS.Add(order);
                        }
                    }
                }
                string idlist = GetQueryString("idlist");
                string sExportFileName = ""; //导出的临时文件的名称
                string sExportFilePath = ""; //导出的临时文件路径
                try
                {
                    HSSFWorkbook wb = BuildSwitchData(lS);
                    string sExportDir = HttpContext.Current.Server.MapPath("~") + "/orderdocument"; //临时保存文件夹
                    sExportFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "待发货订单" + ".xls";
                    sExportFilePath = sExportDir + "/" + sExportFileName;
                    if (!Directory.Exists(sExportDir))
                        Directory.CreateDirectory(sExportDir);
                    using (FileStream file = new FileStream(sExportFilePath, FileMode.Create))
                    {
                        wb.Write(file);
                    }
                }
                catch
                {
                    HttpContext.Current.Response.Write("<script type='text/javascript'>alert('导出发生异常!');window.history.back();</script>");
                    if (File.Exists(sExportFilePath))
                        File.Delete(sExportFilePath);
                    return;
                }
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel; charset=UTF-8";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sExportFileName);
                HttpContext.Current.Response.TransmitFile(sExportFilePath); //将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件
                HttpContext.Current.Response.Flush();
                if (File.Exists(sExportFilePath))
                    File.Delete(sExportFilePath);
                HttpContext.Current.Response.End();
            }
            catch
            {
                HttpContext.Current.Response.Write("<script type='text/javascript'>window.location.href = location.href;parent.layer.msg(导出成功!);</script>");
            }
        }
        #endregion