NPOI導出Excel生成多個sheet


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Reflection;

namespace WebApplication1.Controllers
{
    public class Info
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            List<Info> list = new List<Info>();

            for (int i = 0; i < 10; i++)
            {
                Info info = new Info();
                info.Id = i + 1;
                info.Name = "張三" + (i + 1);
                list.Add(info);
            }
            Dictionary<string, string> columnInfo = new Dictionary<string, string>();
            columnInfo.Add("Id","序號");
            columnInfo.Add("Name", "姓名");
            byte[] btyBytes=null;
            var a = ExportExcelTest<Info>(list, @"F://111.xlsx", ref btyBytes, columnInfo, 2);

            return View();
        }

        #region  NPOI大數據量多個sheet導出

        /// <summary>
        /// 大數據量多個sheet導出
        /// </summary>
        /// <typeparam name="T">數據源實體類</typeparam>
        /// <param name="objList">數據源</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="btyBytes">導出數據流</param>
        /// <param name="columnInfo">顯示列對應數據字典</param>
        /// <param name="listCount">每個sheet包含數據條數</param>
        /// <returns></returns>
        public static bool ExportExcelTest<T>(List<T> objList, string fileName, ref byte[] btyBytes,
Dictionary<string, string> columnInfo = null, int listCount = 10000)
        {
            bool bResult = false;
            //在內存中生成一個Excel文件:
            XSSFWorkbook book = new XSSFWorkbook();
            if (objList != null && objList.Count > 0)
            {
                double sheetCount = Math.Ceiling((double)objList.Count / listCount);
                for (int i = 0; i < sheetCount; i++)
                {
                    ISheet sheet = null;
                    sheet = book.CreateSheet("sheet" + i);
                    sheet.DefaultRowHeight = 20 * 10;
                    List<T> list = new List<T>();
                    list = objList.Skip<T>(listCount * i).Take<T>(listCount).ToList();

                    int rowIndex = 0;
                    int StartColIndex = 0;
                    int colIndex = StartColIndex;

                    //創建表頭樣式
                    ICellStyle style = book.CreateCellStyle();
                    style.Alignment = HorizontalAlignment.CENTER;
                    style.WrapText = true;
                    IFont font = book.CreateFont();
                    font.FontHeightInPoints = 16;
                    font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                    font.FontName = "簡體中文";
                    style.SetFont(font);//HEAD 樣式

                    Type myType = null;
                    myType = objList[0].GetType();
                    //根據反射從傳遞進來的屬性名信息得到要顯示的屬性
                    List<PropertyInfo> myPro = new List<PropertyInfo>();
                    PropertyInfo[] properties = myType.GetProperties();

                    #region 定義表頭
                    int m = 0;
                    if (columnInfo != null)
                    {
                        var rowheader = sheet.CreateRow(0);
                        rowheader.Height = rowheader.Height = 20 * 20;
                        foreach (string cName in columnInfo.Keys)
                        {
                            PropertyInfo p = myType.GetProperty(cName);
                            if (p != null)
                            {
                                myPro.Add(p);
                                rowheader.CreateCell(m).SetCellValue(columnInfo[cName]);
                                m++;
                            }
                        }
                    }
                    #endregion
                    #region 定義表體並賦值
                    //如果沒有找到可用的屬性則結束
                    if (myPro.Count == 0) { return bResult; }
                    foreach (T obj in list)
                    {
                        int n = 0;
                        if (sheet != null)
                        {
                            rowIndex++;
                            var sheetrow = sheet.CreateRow(rowIndex);
                            sheetrow.Height = sheetrow.Height = 20 * 20;
                            foreach (PropertyInfo p in myPro)
                            {
                                dynamic val = p.GetValue(obj, null) ?? "";
                                string valtype = val.GetType().ToString();
                                if (valtype.ToLower().IndexOf("decimal", StringComparison.Ordinal) > -1)
                                {
                                    val = Convert.ToDouble(val);
                                }
                                else if (valtype.ToLower().IndexOf("datetime", StringComparison.Ordinal) > -1)
                                {
                                    val = val.ToString("yyyy-MM-dd HH:mm:ss");
                                    if (val.Equals("0001-01-01 00:00:00"))
                                    {
                                        val = "";
                                    }
                                }
                                sheetrow.CreateCell(n).SetCellValue(val);
                                n++;
                            }
                        }

                    }
                    #endregion
                }
            }
            else
            {
                //在工作薄中建立工作表
                XSSFSheet sheet = book.CreateSheet() as XSSFSheet;
                sheet.SetColumnWidth(0, 30 * 256);
                if (sheet != null) sheet.CreateRow(0).CreateCell(0).SetCellValue("暫無數據!");
            }

          var  fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            book.Write(fs);
            //try
            //{
            //    HttpResponse rs = System.Web.HttpContext.Current.Response;
            //    rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //    rs.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            //    rs.ContentType = "application/vnd.ms-excel";
            //    //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

            //    using (MemoryStream ms = new MemoryStream())
            //    {
            //        book.Write(ms);          
            //        btyBytes = ms.GetBuffer();
            //        rs.AddHeader("Content-Length", btyBytes.Length.ToString());
            //        rs.BinaryWrite(ms.GetBuffer());
            //        ms.Flush();
            //    }
            //}
            //catch (SystemException ex)
            //{
            //    throw ex;
            //}
            //catch (ApplicationException ex)
            //{
            //    throw ex;
            //}
            return bResult;
        }


        #endregion
    }
}

 

 


免責聲明!

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



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