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

来源:http://www.cnblogs.com/shouce/archive/2016/02/22/5206034.html
-Advertisement-
Play Games

//NPOIHelper 類關鍵代碼 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; using NPO


//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();
        }
    }
}

 

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

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天一位同事咨詢Devexpress TreeList控制項綁定自動顯示父子節點對像,但結果是不會顯示帶父子節點關係,而是將所有的節點作為父節點顯示出來了,對像類的代碼如下 public class Item:XPBaseObject { public Item() : base() { } publ
  • $("#找id的")$(".找樣式的") $("div[id]") 選擇所有含有id屬性的div元素 $("input[name='keleyicom']") 選擇所有的name屬性等於'keleyicom'的input元素 $("input[name!='keleyicom']") 選擇所有的na
  • 萬分感謝Fdyo同學給我們帶來的有中文字幕的系列教程! http://zhuanlan.zhihu.com/MSFaith/20364660 下麵是這系列video教程中的一個截圖作為示例,有代碼,有圖片,有彈幕,還有老外! 什麼是通用 Windows 平臺 (UWP) 應用? 通用 Windows
  • 6年過去了,Angular 迎來了2.0版本.Wijmo5與Angular2已經保持了高度一致.Angular 2 要來了,Wijmo 已準備好迎接
  • 回到目錄 Cannot attach the file as database這個異常是在EF的code frist里經常出現的,解決方法很簡單,只要重新啟動一下V11實例即可。 CMD> sqllocaldb.exe stop v11.0 LocalDB instance "v11.0" stop
  • Visual Studio .net從2003到現在的2008,一路走來慢慢強大……從以前的vs2003能自動改亂你的html代碼到現在在vs2008中都能直接對html代碼進行w3c標準驗證並提示了,非常不易。 論壇中也經常有從事.net開發的新手朋友問一些asp.net開發過程中與web標準之間
  • 故事背景大概是這樣的,我廠兩年前給山西晉城人民政府做了一個門戶網站(地址:http://jccq.cn/),運行了一年多固若金湯,duang的有一天市場部門過來說,新聞管理模塊帶視頻的內容播放不了了。 迅雷不及掩耳,我打開網頁F12一看,因為找不到視頻播放的一個swf文件,仔細一看這個文件竟然引用的
  • 1.如果可能儘量使用介面來編程 .NET框架包括類和介面,在編寫程式的時候,你可能知道正在用.NET的哪個類。然而,在這種情況下如果你用.NET支持的介面而不是它的類來編程時,代碼會變得更加穩定、可用性會更高。 請分析下麵的代碼: 1 private void LoadList (object []
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...