ASP.NET中的Excel操作(NPOI方式)


代碼准備:

     一:實體准備

               代碼如下:

    /// <summary>
    /// 一個能添加到將要導出到指定行的實體類型規范
    /// data:{int StartColIndex ? 0, int ColSpan, object Value, bool Center}
    /// </summary>
    public interface IExcelModel
    {
        /// <summary>
        /// 開始列的索引(即使是有合並單元格的情況,也得按未合並單元格時算)
        /// </summary>
        int StartColIndex { get; set; }
        /// <summary>
        /// 這個值一共占多少個單元格
        /// </summary>
        int ColSpan { get; set; }
        /// <summary>
        ////// </summary>
        object Value { get; set; }
        /// <summary>
        /// 是否居中
        /// </summary>
        bool Center { get; set; }
    }

上面的接口代碼,是對要生成的Excel的單元格的規范,Center:表示是否居中,Value:表示顯示的值,ColSpan:表示單元格(列)的合並數,

                                                                     StartColIndex:表示是第幾個單元格,而且跟單元格的合並沒有關系。

              :幫助方法類(Helper)准備
               

 /// <summary> 
        /// 使用NPOI由IList&lt;List&lt;IExcelModel&gt;&gt; datas導出Excel 
        /// </summary> 
        public static void ExportDataSetToExcel(string fileName, HSSFWorkbook book, ISheet sheet, IList<List<IExcelModel>> datas)
        {
            MemoryStream ms = ExportDataSetToExcel(book,sheet,datas) as MemoryStream;
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            ms.Close();
            ms = null;
        }

上面方法中,IList<List<IExcelModel>>表示的是一個List<IExcelModel>的集合,而每一個List<IExcelModel>就是一些個單元格的集合,也就是一行。IList<List<IExcelModel>>就是表示要生成的Excel表是由多行的數據組成的。
fileName表示最后要保存的文件名,要帶后綴名。
上面方法需要引用的方法代碼如下:

private static Stream ExportDataSetToExcel(HSSFWorkbook book, ISheet sheet, IList<List<IExcelModel>> datas)
        {
            // create memory stream
            MemoryStream ms = new MemoryStream();

            // process excel file
            AddDatasToExcelSheet(book, sheet, datas);

            book.Write(ms);
            ms.Flush();
            ms.Position = 0;
            book = null;
            return ms;
        }

上面方法需要引用的方法代碼如下:

        /// <summary>
        /// 將指定數據構造到 Excel 中
        /// </summary>
        /// <param name="book"></param>
        /// <param name="sheet"></param>
        /// <param name="datas"></param>
        public static void AddDatasToExcelSheet(HSSFWorkbook book, ISheet sheet, IList<List<IExcelModel>> datas)
        {
            for (int i = 0; i < datas.Count(); i++)
            {
                AddDatasToExcelRow(book, sheet, i, datas[i]);
            }
        }

        /// <summary>
        /// 添加一個數據集合到將要導出的 Excel 的指定行。
        /// </summary>
        public static void AddDatasToExcelRow(HSSFWorkbook book, ISheet sheet, int rowIndex, List<IExcelModel> datas)
        {
            IRow row = sheet.CreateRow(rowIndex);
            ICellStyle cs = book.CreateCellStyle();
            foreach (dynamic data in datas)
            {
                ICell cell = row.CreateCell(data.StartColIndex);
                cell.SetCellValue(data.Value);
                if (data.ColSpan > 1)
                {
                    CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, data.StartColIndex, data.StartColIndex + data.ColSpan - 1);
                    sheet.AddMergedRegion(cra);
                }
                if (data.Center)
                {
                    //ICellStyle cs = book.CreateCellStyle();//放在這里會報錯:The maximum number of cell styles was exceeded. You can define up to 4000 styles  
 
                    cs.VerticalAlignment = VerticalAlignment.Center;
                    cs.Alignment = HorizontalAlignment.Center;
                    cell.CellStyle = cs;
                }
            }
        }

代碼實戰:

     

            IList<List<IExcelModel>> excelList = new List<List<IExcelModel>>();
            //第一行
            List<IExcelModel> firstRow = new List<IExcelModel>();
               //第一個單元格
                IExcelModel tempFRCell = new ExcelModel() { StartColIndex = 0, ColSpan = 1, Center = true, Value = "" };
               //把第一個單元格添加到第一行中
                firstRow.Add(tempFRCell);
            //把第一個行添加到excelList
            excelList.Add(firstRow);

            //最后的
            HSSFWorkbook book = new HSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            //book.Add(sheet);
            ExcelConstructHelper.ExportDataSetToExcel("示例.xls", book, sheet, excelList);

這樣就可以實現網頁上直接下載一個Excel文件了。

未解決的問題:

       1:單元格的縱向合並
       2:單元格及行的樣式
       如何將這兩個都融合到上面提到的規范中去???
 ----------------------------------------------歡迎批評與交流!!!--------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM