2013年9月11日 星期三

NPOI使用範例


        //匯出Excel ExportToFile
        public static void ExportToFile(GridView gv, string excelName)
        {
            try
            {
                //建立 WorkBook 及試算表
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                HSSFSheet mySheet1 = (HSSFSheet)workbook.CreateSheet(excelName);
                mySheet1.DefaultColumnWidth = 15;         //預設的字元寬度
                //建立標題列 Header
                HSSFRow rowHeader = (HSSFRow)mySheet1.CreateRow(0);
                for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
                {
                    //若有啟用排序,Header會變成 LinkButton
                    LinkButton lb = null;
                    if (gv.HeaderRow.Cells[i].Controls.Count > 0)
                    {
                        lb = gv.HeaderRow.Cells[i].Controls[0] as LinkButton;
                    }
                    string strValue = (lb != null) ? lb.Text : gv.HeaderRow.Cells[i].Text;
                    HSSFCell cell = (HSSFCell)rowHeader.CreateCell(i);
                    cell.SetCellValue(HttpUtility.HtmlDecode(strValue).Trim());
                    NPOI.SS.UserModel.CellStyle cellStyle = workbook.CreateCellStyle();
                    cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;                //設為居中
                    cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_50_PERCENT.index;    //設定背景色
                    cellStyle.FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND;
                    NPOI.SS.UserModel.Font cellFont = workbook.CreateFont();
                    cellFont.Color = NPOI.HSSF.Util.HSSFColor.WHITE.index;                             //設定顏色
                    cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;                //設定粗體字
                    cellStyle.SetFont(cellFont);
                    cell.CellStyle = cellStyle;
                }
                //建立內容列 DataRow
                for (int i = 0; i < gv.Rows.Count; i++)
                {
                    HSSFRow rowItem = (HSSFRow)mySheet1.CreateRow(i + 1);
                    for (int j = 0; j < gv.HeaderRow.Cells.Count; j++)
                    {
                        string value1 = HttpUtility.HtmlDecode(gv.Rows[i].Cells[j].Text).Trim();
                        long number1 = 0;
                        bool isNumeric = long.TryParse(value1, out number1);
                        HSSFCell cell = (HSSFCell)rowItem.CreateCell(j);
                        HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                        //細邊緣
                        //cell.CellStyle.BorderBottom = NPOI.SS.UserModel.CellBorderType.THIN;
                        //cell.CellStyle.BorderLeft = NPOI.SS.UserModel.CellBorderType.THIN;
                        //cell.CellStyle.BorderRight = NPOI.SS.UserModel.CellBorderType.THIN;
                        //cell.CellStyle.BorderTop = NPOI.SS.UserModel.CellBorderType.THIN;
                        //cell.CellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
                        //cell.CellStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
                        //cell.CellStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
                        //cell.CellStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
                        //如果為小計列時,改變背景色
                        if (gv.Rows[i].Cells[0].Text.Contains(":") || gv.Rows[i].Cells[0].Text.Contains("﹞") || gv.Rows[i].Cells[0].Text.Contains("》"))
                        {
                            //設定字型格式
                            NPOI.SS.UserModel.Font cellFont = workbook.CreateFont();
                            cellFont.Color = NPOI.HSSF.Util.HSSFColor.DARK_BLUE.index;             //設定顏色
                            cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;    //設定粗體字
                            cellStyle.SetFont(cellFont);
                            //設定背景色 (不知為啥不是用FillBackgroundColor...)
                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LIGHT_CORNFLOWER_BLUE.index;
                            cellStyle.FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND;
                            //使用者自定的顏色
                            HSSFPalette myColor = workbook.GetCustomPalette();
                            string CColor = "#E8F2FF";
                            byte CR, CG, CB;
                            CColor = CColor.Replace("#", "");
                            CR = Convert.ToByte("0x" + CColor.Substring(0, 2), 16);
                            CG = Convert.ToByte("0x" + CColor.Substring(2, 2), 16);
                            CB = Convert.ToByte("0x" + CColor.Substring(4, 2), 16);
                            //把指定色替換成使用者自定的顏色
                            myColor.SetColorAtIndex(NPOI.HSSF.Util.HSSFColor.LIGHT_CORNFLOWER_BLUE.index, CR, CG, CB);
                        }
                        else
                        {
                            //先把背景色設成某一指定色
                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LIGHT_GREEN.index;
                            cellStyle.FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND;
                            //使用者自定的顏色
                            HSSFPalette myColor = workbook.GetCustomPalette();
                            string CColor = "#F4F9EE";
                            byte CR, CG, CB;
                            CColor = CColor.Replace("#", "");
                            CR = Convert.ToByte("0x" + CColor.Substring(0, 2), 16);
                            CG = Convert.ToByte("0x" + CColor.Substring(2, 2), 16);
                            CB = Convert.ToByte("0x" + CColor.Substring(4, 2), 16);
                            //把指定色替換成使用者自定的顏色
                            myColor.SetColorAtIndex(NPOI.HSSF.Util.HSSFColor.LIGHT_GREEN.index, CR, CG, CB);
                        }
                        if (string.IsNullOrEmpty(value1))
                        {
                            //空白
                            cell.SetCellValue("");
                        }
                        else if (!isNumeric)
                        {
                            //文字格式
                            mySheet1.SetColumnWidth(j, 30 * 256);     //欄位寬度設為30
                            cell.SetCellValue(value1);
                        }
                        else
                        {
                            //數字格式
                            cell.SetCellValue(number1);
                            //自訂呈現格式
                            HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
                            cellStyle.DataFormat = format.GetFormat("#,##0;[RED](#,##0)");
                        }
                        cell.CellStyle = cellStyle;
                    }
                }
                //匯出
                workbook.Write(ms);
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("Attachment; Filename=" + HttpUtility.UrlEncode(excelName) + ".xls"));
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                //釋放資源
                workbook = null;
                ms.Close();
                ms.Dispose();
            }
            catch (Exception)
            { }
        }

沒有留言:

張貼留言