NPOI 导出Excel 功能

NPOI 是 .net 基于POI基础上针对于C#的封装使用

关键字:workbook  (工作簿)   sheet (单个簿)   row (行)  cell(单元格) CellStyle (单元格样式)

流程:

1 :创建一个工作簿   IWorkbook wb = new XSSFWorkbook();

 2:创建一个sheet    ISheet sh = wb.CreateSheet("ReservationList"); 创建可以设置名字

3:创建行    IRow row0 = sh.CreateRow(0);   IRow row1 = sh.CreateRow(1);

4:创建cell 单元格    ICell Cell1 = row0.CreateCell(0);

5:设置内容以及样式

创建样式:icellstyle  cellstyle1=wb.creatcellstyle();    IFont font1 = wb.CreateFont(); 

设置样式:  (样式是什么样 字体是什么  样式选用什么字体)

cellstyle1= NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.NewPromotionTitle);

font1.Color = HSSFColor.Red.Index;

cellstyle1.setfont=font1;

 row0.Height = 30 * 20;

具体style样式设置

cellstyle1.WrapText = true; //自动换行

cellstyle1.indention= 0; //缩进

cellstyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平
cellstyle1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直

具体font样式设置

 font1.Boldweight =(short)NPOI.SS.UserModel.FontBoldWeight.Bold;//加粗

 font1.FontName = "字体";
 font1.FontHeightInPoints = 15;
 font1.FontHeight = "高度 字号乘以20";

赋予样式内容 ( 行 单元格 赋值 以及匹配 样式)

Cell1.setvalue();    Cell1.cellstyle=cellstyle1;  
 

6:导出到excel中  ExportXslx方法   npoifunction.cs中

 filename = filename + ".xlsx";
 String serverMapPath = ConfigurationManager.AppSettings["UploadPath"];
NPOIfunctions.ExportXslx(wb, filename, "ReservationList", serverMapPath);

举例:

这么多列:

 List<string> heads = new List<string>()
                {
                    "Booking Date","Booking no", "Tour Code", "Departure Date","Traveler Name","Pax no", "Dep City", "Airline",
                    "Sabre Record","Authorize Charge","Sabre Charge","Total Fare", "Payment","Agent","Branch","Profile",
                    "Ocean ID", "Extension","Promotion Code","Promotion","Optional Tours","Insurance","InsuranceType","Bus",
                    "Return Date",  "Package Category", "ContactName","GroupOn",  "Visa", "City", "State",
                    "Address1", "Address2", "ZipCode", "RemainBalance", "Shipping Info"
                };

 

导出功能:List<ReservationViewModel> list 是要导出的内容数据

 public void PrintReservationList(List<ReservationViewModel> list, List<string> heads, String title, String filename)
        {
            //System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            //stopwatch.Start(); // 开始监视代码运行时间 
            IWorkbook wb = new XSSFWorkbook();
            ISheet sh = wb.CreateSheet("ReservationList");
            ICellStyle style = wb.CreateCellStyle();
            //设置表 title格式
            style = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.NewPromotionTitle);
            sh.AddMergedRegion(new CellRangeAddress(0, 0, 0, heads.Count - 1)); //合并第一行0-Count个格
            IRow row0 = sh.CreateRow(0);
            row0.Height = 30 * 20;
            ICell icellTitleNameP1 = row0.CreateCell(0);
            title = "ReservationViewList";
            icellTitleNameP1.SetCellValue(title);
            icellTitleNameP1.CellStyle = style;

            IRow row1 = sh.CreateRow(1);
            row1.Height = 30 * 20;
            ICellStyle styleRow2 = wb.CreateCellStyle();
            styleRow2 = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.ReportColumnName);
            IRow row2 = sh.CreateRow(2);

            foreach (var fieldName in heads) //列    
            {
                ICell cell = row2.CreateCell(heads.IndexOf(fieldName));
                cell.SetCellValue(fieldName);
                cell.CellStyle = styleRow2;
                int columnWidth = sh.GetColumnWidth(heads.IndexOf(fieldName)) / 256; //获取当前列宽度  
                int length = Encoding.UTF8.GetBytes(cell.ToString()).Length; //获取表格中字符串长度
                if (columnWidth < length)
                {
                    columnWidth = length + 2; //稍微长一些
                }

                sh.SetColumnWidth(heads.IndexOf(fieldName), columnWidth * 256);
            }
            styleRow2 = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.ReportColumnName);


            // 数据处理
            ICellStyle styleCellNor = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.ReportContent); //格式要放在循环外面。
            ICellStyle styleCellSta = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.ReportContent);
            IFont font = wb.CreateFont();
            font.Color = HSSFColor.Red.Index;
            styleCellSta.SetFont(font);

            #region 填充数据
            Int32 workbookRowIndex = 3;
            foreach (var tourOrder in list)
            {
                tourOrder.tourorderMod = CommonFunction.GetNewDate(tourOrder.tourorderMod);
                IRow contentRow = sh.CreateRow(workbookRowIndex);
                foreach (var fieldName in heads)
                {
                    ICell contentCell = contentRow.CreateCell(heads.IndexOf(fieldName));
                    styleCellNor.Alignment = HorizontalAlignment.Center;

                    contentCell.CellStyle = styleCellNor;
                    contentCell.CellStyle.WrapText = true;
                    switch (fieldName)
                    {
                        case "Booking no":
                            contentCell.SetCellValue(tourOrder.ConfirmationId);
                            break;
                        case "Tour Code":
                            String privatourStr = String.Format("{0}", !String.IsNullOrWhiteSpace(tourOrder.PrivateTourType) && !String.Equals(tourOrder.PrivateTourType, "OP1", StringComparison.CurrentCultureIgnoreCase) ?"("+ tourOrder.PrivateTourType+")" : String.Empty);
                            contentCell.SetCellValue(String.Format("{0}{1}{2}", tourOrder.Code, tourOrder.IsEnglish ? "(EN)" : String.Empty, privatourStr));
                            break;
                        case "Traveler Name":
                            string name = string.Empty;
                            foreach (var item in tourOrder.TravelsName)
                            {
                                name += PA_CommonFunction.GetNewName(item, 3) + "\r\n";
                            }
                            contentCell.SetCellValue(name);
                            break;
                        case "Pax no":
                            contentCell.SetCellValue(tourOrder.NumberOfTravel);
                            break;
                        case "Dep City":
                            contentCell.SetCellValue(tourOrder.DepartureCity);
                            break;
                        case "Airline":
                            contentCell.SetCellValue(tourOrder.Airline);
                            break;
                        case "Sabre Record":
                            string sabreRecord = null;
                            foreach (var z in tourOrder.Pnr)
                            {
                                sabreRecord = sabreRecord + " " + z;
                            }
                            contentCell.SetCellValue(sabreRecord);
                            break;
                        case "Payment":
                            String payment = String.Empty;
                            if (tourOrder.IsPendingBooking)
                            {
                                payment = "Pending";
                            }
                            else
                            {
                                String status = tourOrder.CancelOrModified == 2 && tourOrder.Status != "Cancelled" && tourOrder.Status != "Modified" ? "[Modified]" : (tourOrder.CancelOrModified == 1 && tourOrder.Status != "Cancelled" && tourOrder.Status != "Modified" ? "[Cancelled]" : "");
                                payment = String.Format("{0}{1}", (!String.IsNullOrWhiteSpace(status) ? String.Format("{0}{1}", status, Convert.ToChar(10)) : status), tourOrder.Status);
                            }
                            contentCell.SetCellValue(payment);
                            break;
                        case "Agent":
                            contentCell.SetCellValue(tourOrder.AgentInfo);
                            break;
                        case "Branch":
                            contentCell.SetCellValue(tourOrder.SalesInfo);
                            break;
                        case "Profile":
                            contentCell.SetCellValue(tourOrder.Profile);
                            break;
                        case "Ocean ID":
                            contentCell.SetCellValue(tourOrder.OceanId);
                            break;
                        case "Promotion Code":
                            string promCode = null;
                            foreach (var x in tourOrder.PromotionCodes)
                            {
                                promCode += x + ",";
                            }
                            contentCell.SetCellValue(!String.IsNullOrEmpty(promCode) ? promCode.Trim(',') : String.Empty);
                            break;
                        case "Promotion":
                            contentCell.SetCellValue(tourOrder.Promotion);
                            break;
                        case "InsuranceType":
                            String insuranceType = String.Empty;
                            switch (tourOrder.InsuranceType)
                            {
                                case InsuranceType.P1:
                                    insuranceType = "Travelex28";
                                    break;
                                case InsuranceType.T2:
                                    insuranceType = "Travelex";
                                    break;
                            }
                            contentCell.SetCellValue(insuranceType);
                            break;
                        case "Bus":
                            contentCell.SetCellValue(tourOrder.Bus);
                            break;
                        case "Package Category":
                            contentCell.SetCellValue(tourOrder.PackageHotelGroups);
                            break;
                        case "ContactName":
                            contentCell.SetCellValue(tourOrder.ContactName);
                            break;
                        case "Visa":
                            contentCell.SetCellValue(tourOrder.Visa);
                            break;
                        case "City":
                            contentCell.SetCellValue(tourOrder.City);
                            break;
                        case "State":
                            contentCell.SetCellValue(tourOrder.State);
                            break;
                        case "Address1":
                            contentCell.SetCellValue(tourOrder.Address1);
                            break;
                        case "Address2":
                            contentCell.SetCellValue(tourOrder.Address2);
                            break;
                        case "ZipCode":
                            contentCell.SetCellValue(tourOrder.ZipCode);
                            break;
                        case "Shipping Info":
                            contentCell.SetCellValue(tourOrder.ShippingInfo);
                            break;
                        case "Booking Date":
                            if (tourOrder.BookingDate != null)
                            {
                                contentCell.SetCellValue(Convert.ToDateTime(tourOrder.BookingDate.ToString()));
                            }
                            break;
                        case "Return Date":
                            if (tourOrder.tourorderMod.TripSetting.NewReturnDate != null)
                            {
                                contentCell.SetCellValue(Convert.ToDateTime(tourOrder.tourorderMod.TripSetting.NewReturnDate.ToString()));
                            }
                            break;
                        case "Departure Date":
                            if (tourOrder.tourorderMod.TripSetting.NewDepartureDate != null)
                            {
                                contentCell.SetCellValue(Convert.ToDateTime(tourOrder.tourorderMod.TripSetting.NewDepartureDate.ToString()));
                            }
                            break;
                        case "Authorize Charge":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.AuthorizeChargeForReport));
                            break;
                        case "Sabre Charge":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.SabreChargeForReport));
                            break;
                        case "Total Fare":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.TotalAmountForReport));
                            break;
                        case "Optional Tours":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.OptionalToursPriceForReport));
                            break;
                        case "Insurance":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.InsurancePriceForReport));
                            break;
                        case "Extension":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.ExtensionTotalForReport));
                            break;
                        case "GroupOn":
                            contentCell.SetCellValue(Convert.ToDouble(tourOrder.GroupOnPriceForReport));
                            break;
                        case "RemainBalance":
                            decimal rb = 0;
                            if (tourOrder.RemainBalance > 0 && (tourOrder.Status == "Ticketed" || tourOrder.Status == "Sent"))
                            {
                                rb = tourOrder.RemainBalance;
                            }
                            contentCell.SetCellValue(Convert.ToDouble(rb));
                            break;

                    }
                }
                workbookRowIndex++;
            }
            #endregion

            #region 格式化表格格式
            for (var h = 0; h < heads.Count; h++)
            {
                ICellStyle cellsty = styleCellNor;
                var columnName = heads[h];
                int columnWidth = sh.GetColumnWidth(h) / 256; //获取当前列宽度  
                switch (columnName)
                {
                    case "Departure Date":
                    case "Return Date":
                        cellsty = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.ShortDateForReservation);
                        break;
                    case "Address2":
                    case "Tour Code":
                    case "Traveler Name":
                        columnWidth += 12;
                        break;
                    case "Booking Date":
                        columnWidth += 8;
                        cellsty = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.LongDate);
                        break;
                    case "Payment":
                        columnWidth += 4;
                        cellsty = styleCellSta;
                        break;
                    case "Authorize Charge":
                    case "Sabre Charge":
                    case "Total Fare":
                    case "Extension":
                    case "Insurance":
                    case "RemainBalance":
                    case "GroupOn":
                        columnWidth = 16;
                        cellsty = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.Accounting2);
                        break;
                    case "Optional Tours":
                        columnWidth = 14;
                        cellsty = NPOIfunctions.SetCellStyle(wb, NPOIfunctions.Stylexls.Accounting);
                        break;
                    case "Address1":
                    case "Profile":
                    case "Branch":
                    case "Agent":
                        columnWidth += 22;
                        break;
                    case "Shipping Info":
                        columnWidth += 36;
                        break;
                    default:
                        columnWidth += 4;
                        break;
                }
                NPOIfunctions.FillWholeColStyle(sh, h, cellsty, columnWidth, 1);
            }
            #endregion

            //stopwatch.Stop(); // 停止监视
            //TimeSpan timespan = stopwatch.Elapsed; // 获取当前实例测量得出的总时间
            //string hours = timespan.TotalHours.ToString("#0.00000000 "); // 总小时
            //string minutes = timespan.TotalMinutes.ToString("#0.00000000 "); // 总分钟
            //string seconds = timespan.TotalSeconds.ToString("#0.00000000 "); // 总秒数
            //string milliseconds = timespan.TotalMilliseconds.ToString("#0.00000000 "); // 总毫秒数
            //表,第一行标题,第二行为空。
            filename = filename + ".xlsx";
            //ExportXslx(wb, filename, "ReservationList");
            String serverMapPath = ConfigurationManager.AppSettings["UploadPath"];
            NPOIfunctions.ExportXslx(wb, filename, "ReservationList", serverMapPath);
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值