NPOI導出EXCEL數據量大,分多個sheet顯示數據


 

//NPOIHelper  類關鍵代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Collections;
using System.Web;

namespace Yikeba_htmlConverter
{
    public class NPOIHelper
    {
        /// <summary>
        /// 列名集合
        /// </summary>
        public static System.Collections.SortedList ListColumnsName;
        /// <summary>
        /// 導出Excel通過文件路徑
        /// </summary>
        /// <param name="dtSource">DataTable數據源</param>
        /// <param name="filePath">文件路徑</param>
        public static void ExportExcel(DataTable dtSource, string filePath)
        {
            if (ListColumnsName == null || ListColumnsName.Count == 0)
                throw (new Exception("請對ListColumnsName設置要導出的列名!"));

            HSSFWorkbook excelWorkbook = CreateExcelFile();
            InsertRow(dtSource, excelWorkbook);
            SaveExcelFile(excelWorkbook, filePath);
        }

        /// <summary>
        /// 導出Excel通過流
        /// </summary>
        /// <param name="dtSource">DataTable數據源</param>
        /// <param name="excelStream">流操作</param>
        public static void ExportExcel(DataTable dtSource, Stream excelStream)
        {
            if (ListColumnsName == null || ListColumnsName.Count == 0)
                throw (new Exception("請對ListColumnsName設置要導出的列明!"));

            HSSFWorkbook excelWorkbook = CreateExcelFile(); //新建一個工作區域
            InsertRow(dtSource, excelWorkbook);//導入數據的方法
            SaveExcelFile(excelWorkbook, excelStream);//保存excel
        }

        /// <summary>
        /// 保存Excel文件通過路徑
        /// </summary>
        /// <param name="excelWorkBook"></param>
        /// <param name="filePath"></param>
        protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, string filePath)
        {
            FileStream file = null;
            try
            {
                file = new FileStream(filePath, FileMode.Create);
                excelWorkBook.Write(file);
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }
        /// <summary>
        /// 保存Excel文件
        /// </summary>
        /// <param name="excelWorkBook"></param>
        /// <param name="filePath"></param>
        protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, Stream excelStream)
        {
            try
            {
                excelWorkBook.Write(excelStream);
            }
            finally
            {

            }
        }

        /// <summary>
        /// 創建Excel文件
        /// </summary>
        /// <param name="filePath"></param>
        protected static HSSFWorkbook CreateExcelFile()
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            return hssfworkbook;
        }

        /// <summary>
        /// 創建excel表頭
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="excelSheet"></param>
        protected static void CreateHeader(HSSFSheet excelSheet)
        {
            int cellIndex = 0;
            //循環導出列
            foreach (System.Collections.DictionaryEntry de in ListColumnsName)
            {
                HSSFRow newRow = excelSheet.CreateRow(0);
                HSSFCell newCell = newRow.CreateCell(cellIndex);
                newCell.SetCellValue(de.Value.ToString());
                cellIndex++;
            }
        }

        /// <summary>
        /// 插入數據行
        /// </summary>
        protected static void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
        {
            int rowCount = 0;
            int sheetCount = 1;
            HSSFSheet newsheet = null;

            //循環數據源導出數據集
            newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount); //創建第一個sheet
            CreateHeader(newsheet);//加載sheet的頭信息
            foreach (DataRow dr in dtSource.Rows)  //循環DataTable里面的數據行
            {
                rowCount++;
                //超出10000條數據 創建新的工作簿
                if (rowCount == 10000)   //超過10000行數據就新建一個sheet
                {
                    rowCount = 1;
                    sheetCount++;
                    newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount); //新建sheet
                    CreateHeader(newsheet);//新建sheet的頭信息
                }

                HSSFRow newRow = newsheet.CreateRow(rowCount);//創建sheet的當前行
                InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook);  //往當前行里面的每一列循環添加數據
            }
        }

        /// <summary>
        /// 導出數據行
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="drSource"></param>
        /// <param name="currentExcelRow"></param>
        /// <param name="excelSheet"></param>
        /// <param name="excelWorkBook"></param>
        protected static void InsertCell(DataTable dtSource, DataRow drSource, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
        {
            for (int cellIndex = 0; cellIndex < ListColumnsName.Count; cellIndex++)
            {
                //列名稱
                string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
                HSSFCell newCell = null;
                System.Type rowType = drSource[cellIndex].GetType();
                string drValue = drSource[cellIndex].ToString().Trim();
                switch (rowType.ToString())
                {
                    case "System.String"://字符串類型
                        drValue = drValue.Replace("&", "&");
                        drValue = drValue.Replace(">", ">");
                        drValue = drValue.Replace("<", "<");
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue(drValue);
                        break;
                    case "System.DateTime"://日期類型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue(dateV);

                        //格式化顯示
                        HSSFCellStyle cellStyle = excelWorkBook.CreateCellStyle();
                        HSSFDataFormat format = excelWorkBook.CreateDataFormat();
                        cellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
                        newCell.CellStyle = cellStyle;

                        break;
                    case "System.Boolean"://布爾型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue(boolV);
                        break;
                    case "System.Int16"://整型
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue(intV.ToString());
                        break;
                    case "System.Decimal"://浮點型
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue(doubV);
                        break;
                    case "System.DBNull"://空值處理
                        newCell = currentExcelRow.CreateCell(cellIndex);
                        newCell.SetCellValue("");
                        break;
                    default:
                        throw (new Exception(rowType.ToString() + ":類型數據無法處理!"));
                }
            }
        }
    }

    //排序實現接口 不進行排序 根據添加順序導出
   
    public class NoSort : System.Collections.IComparer
    {
        public int Compare(object x, object y)
        {
            return -1;
        }
    }
}

//新建一個WebForm1頁面測試

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yikeba_htmlConverter;
using System.Xml;
using System.IO;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //導出數據列 實現根據添加順序導出列
            NPOIHelper.ListColumnsName = new SortedList(new NoSort());
            NPOIHelper.ListColumnsName.Add("MemberName", "姓名");
            NPOIHelper.ListColumnsName.Add("username", "賬號");
            NPOIHelper.ListColumnsName.Add("starttime", "登陸時間");
            NPOIHelper.ListColumnsName.Add("lasttime", "在線到期時間");
            NPOIHelper.ListColumnsName.Add("state", "狀態");
            Response.Clear();
            Response.BufferOutput = false;
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            string filename = HttpUtility.UrlEncode(DateTime.Now.ToString("在線用戶yyyyMMdd"));
            Response.AddHeader("Content-Disposition", "attachment;filename=DownExcel" + ".xls");
            Response.ContentType = "application/ms-excel";

            string str = "<table><tr><td>CSBT-120906-TG6</td><td>廖建軍</td><td>LIAO</td><td>JIANJUN</td><td>男</td></tr><tr><td>CSBT-120906-TG7</td><td>王漢剛</td><td>WANG</td><td>HANGANG</td><td>男</td></tr></table>";
            str = "<?xml version=\"1.0\" standalone=\"yes\"?>" + str;

            //清洗
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(str);

            XmlNodeList nodes = doc.SelectNodes("table/tr");
            foreach (XmlElement node in nodes)
            {
                node.Attributes.RemoveAll(); //這里把Tr所有的屬性都去掉

                for (int i = 0; i < node.ChildNodes.Count; i++) //列的循環,為每個列指定名稱
                {
                    XmlNode n = doc.CreateNode(XmlNodeType.Element, "col" + i.ToString(), "");
                    n.InnerXml = node.ChildNodes[i].InnerXml;
                    node.ReplaceChild(n, node.ChildNodes[i]);
                }
            }
            //導入Dataset
            StringReader tr = new StringReader(doc.InnerXml);
            DataSet ds = new DataSet();
            ds.ReadXml(tr);
            DataTable dtSource = ds.Tables[0];
           // DataTable dtSource = new DataTable();
            NPOIHelper.ExportExcel(dtSource, Response.OutputStream);
            Response.Close();
        }
    }
}

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//輔助

http://www.cnblogs.com/atao/archive/2009/09/24/1572980.html  生成下拉列表

http://www.cnblogs.com/tonyqus/category/182110.html    更多更詳細的execl用法 
http://www.cnblogs.com/atao/archive/2009/09/13/1565644.html  處理日期函數
http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html  NPOI使用Excel公式、 單元格操作、創建圖形等高級功能


免責聲明!

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



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