NPOI 匯出EXCEL 檔案

            try
            {
                // 定义要写入的Excel文件地址
                string excel = Server.MapPath(@"~\template\memberlist.xls");
                // 创建Excel文件流
                using (FileStream fileStream = new FileStream(excel, FileMode.Open, FileAccess.Read))
                {

                    // 创建NPOI的Excel操作对象
                    IWorkbook hssfWorkbook = null;
                    if (excel.IndexOf(".xlsx") > 0) // 2007版本
                        hssfWorkbook = new XSSFWorkbook(fileStream);
                    else if (excel.IndexOf(".xls") > 0) // 2003版本
                        hssfWorkbook = new HSSFWorkbook(fileStream);

                    fileStream.Close();

                    /// <summary>
                    /// EmployeesSheet 欄位設定
                    /// </summary>
                    /// <returns></returns>
                    //

                    MemberListViewModel EmployeesSheetValue = EmployeesViewModel(SubContractor);
                    string SubcontractorsIDName = EmployeesSheetValue.SubcontractorsModel.SubContractorID + EmployeesSheetValue.SubcontractorsModel.SubContractorName;

                    int st = hssfWorkbook.GetSheetIndex(SubcontractorsIDName);
                    if (st > -1)
                    {
                        hssfWorkbook.RemoveSheetAt(hssfWorkbook.GetSheetIndex(SubcontractorsIDName));
                    }
                    ISheet EmployeesSheet = hssfWorkbook.GetSheet("工作表1");
                    hssfWorkbook.SetSheetName(hssfWorkbook.GetSheetIndex("工作表1"), SubcontractorsIDName);

                    EmployeesSheet.GetRow(0).GetCell(1).SetCellValue(EmployeesSheetValue.CompanyModel.CompanyName);
                    EmployeesSheet.GetRow(1).GetCell(2).SetCellValue(EmployeesSheetValue.SubcontractorsModel.SubContractorID);
                    EmployeesSheet.GetRow(2).GetCell(2).SetCellValue(EmployeesSheetValue.SubcontractorsModel.SubContractorName);

                    // 根據DB建立CodeBase SHEET
                    ISheet CodeBaseSheet = hssfWorkbook.CreateSheet("CodeBase");

                    // 遍历数据表行数据写入工作表

                    for (int i = 0, iLength = data.Rows.Count; i < iLength; i++)
                    {
                        //创建工作表数据行
                        IRow CodeBaserow = CodeBaseSheet.CreateRow(i);
                        // 遍历行数据写入工作表
                        for (int j = 0, jLength = data.Columns.Count; j < jLength; j++)
                        {
                            // 获取数据
                            object value = data.Rows[i][j];
                            // 创建单元格

                            ICell cell = CodeBaserow.CreateCell(j);
                            // 设置单元格数据
                            if (value == null)
                            {
                                cell.SetCellValue("");
                            }
                            else
                            {
                                cell.SetCellValue(value.ToString());
                            }
                        }
                    }
                    //狀態欄位 Y/N
                    CodeBaseSheet.GetRow(0).CreateCell(1).SetCellValue("Y");
                    CodeBaseSheet.GetRow(1).CreateCell(1).SetCellValue("N");

                    //EXCEL建立公式 工種代碼下拉選單
                    CellRangeAddressList regions = new CellRangeAddressList(5, 65535, 4, 4);
                    HSSFName range = (HSSFName)hssfWorkbook.CreateName();
                    range.RefersToFormula = "CodeBase!$A:$A";
                    range.NameName = "dicRange";

                    DVConstraint constraint2 = DVConstraint.CreateFormulaListConstraint("dicRange");
                    HSSFDataValidation dataValidate2 = new HSSFDataValidation(regions, constraint2);
                    dataValidate2.CreateErrorBox("error", "輸入工種代碼格式不正確");
                    EmployeesSheet.AddValidationData(dataValidate2);
                    // 工安訓練 職安証照 EXCEL設置下拉選單
                    CellRangeAddressList StatusRange = new CellRangeAddressList(5, 65535, 8, 9);
                    HSSFName StatusHSSFName = (HSSFName)hssfWorkbook.CreateName();
                    StatusHSSFName.RefersToFormula = "CodeBase!$B$1:$B$2";
                    StatusHSSFName.NameName = "StatusRange";
                    DVConstraint Statusconstraint = DVConstraint.CreateFormulaListConstraint("StatusRange");
                    HSSFDataValidation StatusValidate = new HSSFDataValidation(StatusRange, Statusconstraint);
                    StatusValidate.CreateErrorBox("error", "輸入格式不正確");
                    EmployeesSheet.AddValidationData(StatusValidate);
                    // 勞保卡 承諾書 EXCEL設置下拉選單
                    CellRangeAddressList StatusRange2 = new CellRangeAddressList(5, 65535, 11, 12);
                    HSSFDataValidation StatusValidate2 = new HSSFDataValidation(StatusRange2, Statusconstraint);
                    StatusValidate2.CreateErrorBox("error", "輸入格式不正確");
                    EmployeesSheet.AddValidationData(StatusValidate2);



                    HSSFCellStyle oStyle = (HSSFCellStyle)hssfWorkbook.CreateCellStyle();

                    //設定上下左右的框線
                    oStyle.BorderBottom = BorderStyle.Thin;
                    oStyle.BorderLeft = BorderStyle.Thin;//細實線
                    oStyle.BorderRight = BorderStyle.Thin;
                    oStyle.BorderTop = BorderStyle.Thin;

                    for (int i = 5, iLength = 37; i < iLength; i++)
                    {
                        //创建工作表数据行
                        IRow EmployeesBaserow = EmployeesSheet.CreateRow(i);
                        // 遍历行数据写入工作表
                        for (int j = 0, jLength = 14; j < jLength; j++)
                        {
                            ICell cell = EmployeesBaserow.CreateCell(j);
                            cell.CellStyle = oStyle;

                        }
                    }
                    //0:顯示 1:隱藏 CodeBase SHEET
                    hssfWorkbook.SetSheetHidden(1, 1);

                    byte[] p_By;
                    // 保存excel文件內容
                    using (MemoryStream ms = new MemoryStream())
                    {
                        hssfWorkbook.Write(ms);

                        p_By = ms.ToArray();

                    }

                    string filename = Server.UrlEncode(SubcontractorsIDName + "名冊");

                    Response.AddHeader("content-disposition", "attachment;  filename=" + filename + ".xls");
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.BinaryWrite(p_By);

                    Response.Flush();
                    Response.End();
                }

            }
            catch (Exception ex)
            {
               
                throw new Exception(ex.Message);
            }


參考資料
http://www.cnblogs.com/luxiaoxun/p/3374992.html

用NPOI操作EXCEL--生成下拉列表

留言

這個網誌中的熱門文章

具有潛在危險 Request.Form 的值已從用戶端

ajax錯誤時,回傳error message內容