C#導出Excel源碼

excel

C#導出Excel方法有多種﹐常用的按照Microsoft 的方法如下:
1﹑"Use Automation to Transfer Data Cell by Cell "
2﹑"Use Automation to Transfer an Array of Data to a Range on a Worksheet "
3﹑"Use Automation to Transfer an ADO Recordset to a Worksheet Range "
4﹑"Use Automation to Create a QueryTable on a Worksheet"
5﹑"Use the Clipboard"
6﹑"Create a Delimited Text File that Excel Can Parse into Rows and Columns"
7﹑"Transfer Data to a Worksheet Using ADO.NET "
在此本人主要使用第4種方法:即利用Excel的QueryTable導出海量數據。
要利用Excel的QueryTable的方法﹐首先需要引用Excel類庫。這個我就不多說了。
第二步就是新增一個窗體文件﹐為簡單起見﹐只在窗體上加一個button按鈕。在Button Click事件中加入操作的代碼。整個操作﹐我只在一個類中實現﹐源碼附貼如下(office2003)﹕
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication3
{
    public partial class Form1 : Form
    {
        private Microsoft.Office.Interop.Excel.Application m_objExcel = null;
        private Microsoft.Office.Interop.Excel.Workbooks m_objBooks = null;
        private Microsoft.Office.Interop.Excel._Workbook m_objBook = null;
        private Microsoft.Office.Interop.Excel.Sheets m_objSheets = null;
        private Microsoft.Office.Interop.Excel._Worksheet m_objSheet = null;
        private Microsoft.Office.Interop.Excel.Range m_objRange = null;
        //private Microsoft.Office.Interop.Excel.Font m_objFont = null;
        //private Microsoft.Office.Interop.Excel.QueryTables m_objQryTables = null;
        private Microsoft.Office.Interop.Excel._QueryTable m_objQryTable = null;
        // Frequenty-used variable for optional arguments.
        private object m_objOpt = System.Reflection.Missing.Value;
        //DataBase-used variable
        private System.Data.SqlClient.SqlConnection sqlConn = null;
        private string strConnect = "Data Source='192.168.168.253';Password = SHS;User ID=SHS;Initial Catalog=TEST_KM_ERP";
        private System.Data.SqlClient.SqlCommand sqlCmd = null;

        //Sheets variable
        private double dbSheetSize = 65535;//the hight limit number in one sheet
        private int intSheetTotalSize = 0;//total record can divied sheet number
        private double dbTotalSize = 0;//record total number

        public Form1()
        {
            InitializeComponent();
        }

        private int GetTotalSize()
        {
            sqlConn = new System.Data.SqlClient.SqlConnection(strConnect);
            sqlCmd = new System.Data.SqlClient.SqlCommand("Select Count(*) From PD_WORKBIL_MST", sqlConn);
            sqlConn.Open();
            dbTotalSize = (int)sqlCmd.ExecuteScalar();
            sqlConn.Close();
            return (int)Math.Ceiling(dbTotalSize / this.dbSheetSize);
        }
        private void DeclareExcelApp()
        {
            m_objExcel = new Microsoft.Office.Interop.Excel.Application();
            m_objBooks = (Microsoft.Office.Interop.Excel.Workbooks)m_objExcel.Workbooks;
            m_objBook = (Microsoft.Office.Interop.Excel._Workbook)(m_objBooks.Add(m_objOpt));
            m_objSheets = (Microsoft.Office.Interop.Excel.Sheets)m_objBook.Worksheets;
            intSheetTotalSize = GetTotalSize();
            if (intSheetTotalSize <= 3)
            {
                if (this.dbTotalSize <= this.dbSheetSize)
                {
                    this.ExportDataByQueryTable(1, false);
                    return;
                }
                else if (this.dbTotalSize <= this.dbSheetSize * 2)
                {
                    this.ExportDataByQueryTable(1, false);
                    this.ExportDataByQueryTable(2, true);
                    return;
                }
                else
                {
                    this.ExportDataByQueryTable(1, false);
                    this.ExportDataByQueryTable(2, true);
                    this.ExportDataByQueryTable(3, true);
                    return;
                }
            }
            for (int i = 3; i < intSheetTotalSize; i++)
            {
                m_objSheets.Add(m_objOpt, m_objSheets.get_Item(i), m_objOpt, m_objOpt);
            }
            ExportDataByQueryTable(1, false);
            for (int i = 2; i <= m_objSheets.Count; i++)
            {
                ExportDataByQueryTable(i,true);
            }
        }
        private void SaveExcelApp()
        {
            string excelFileName = string.Empty;
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "*.xls|*.*";
            if (sf.ShowDialog() == DialogResult.OK)
            {
                excelFileName = sf.FileName;
            }
            else
            {
                return;
            }
            m_objBook.SaveAs(excelFileName, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
        }
        private void ExportDataByQueryTable(int intSheetNumber,bool blIsMoreThan)
        {
            string strQuery = string.Empty;
            if (blIsMoreThan)
            {
                strQuery = "Select Top " +
                this.dbSheetSize + " * From PD_WORKBIL_MST Where Not  CMPID In (Select Top " +
                dbSheetSize * (intSheetNumber-1) + "  CMPID From PD_WORKBIL_MST)";
            }
            else
            {
                strQuery = "Select Top " +this.dbSheetSize + " * From PD_WORKBIL_MST ";

            }
            m_objSheet = (Microsoft.Office.Interop.Excel._Worksheet)(m_objSheets.get_Item(intSheetNumber));
            m_objSheet.get_Range("A1", m_objOpt).set_Value(m_objOpt, "中文測試一");
            m_objSheet.get_Range("B1", m_objOpt).set_Value(m_objOpt, "中文測試二");
            m_objSheet.get_Range("C1", m_objOpt).set_Value(m_objOpt, "中文測試三");
            m_objSheet.get_Range("D1", m_objOpt).set_Value(m_objOpt, "中文測試四");
            m_objSheet.get_Range("E1", m_objOpt).set_Value(m_objOpt, "中文測試五");
            m_objRange = m_objSheet.get_Range("A2", m_objOpt);
            m_objQryTable = m_objSheet.QueryTables.Add("OLEDB;Provider=SQLOLEDB.1;" + strConnect, m_objRange, strQuery);
            m_objQryTable.RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertEntireRows;
            m_objQryTable.FieldNames = false;
            m_objQryTable.Refresh(false);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DeclareExcelApp();
            SaveExcelApp();
        }
    }
}
使用office2000的話﹐好像類庫有些不同﹐為給大家一個比較﹐也將源碼附貼如下﹕
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        Excel.Range m_objRange = null;
        Excel.Application m_objExcel = null;
        Excel.Workbooks m_objBooks = null;
        Excel._Workbook m_objBook = null;
        Excel.Sheets m_objSheets = null;
        Excel._Worksheet m_objSheet = null;
        Excel.QueryTable m_objQryTable = null;
        object m_objOpt = System.Reflection.Missing.Value;
        //DataBase-used variable
        private System.Data.SqlClient.SqlConnection sqlConn = null;
        private string strConnect = "Data Source='192.168.168.253';Password = SHS;User ID=SHS;Initial Catalog=TEST_KM_ERP";
        private System.Data.SqlClient.SqlCommand sqlCmd = null;

        //Sheets variable
        private double dbSheetSize = 65535;//the hight limit number in one sheet
        private int intSheetTotalSize = 0;//total record can divied sheet number
        private double dbTotalSize = 0;//record total number

        public Form1()
        {
            InitializeComponent();
        }

        private int GetTotalSize()
        {
            sqlConn = new System.Data.SqlClient.SqlConnection(strConnect);
            sqlCmd = new System.Data.SqlClient.SqlCommand("Select Count(*) From PD_WORKBIL_MST", sqlConn);
            sqlConn.Open();
            dbTotalSize = (int)sqlCmd.ExecuteScalar();
            sqlConn.Close();
            return (int)Math.Ceiling(dbTotalSize / this.dbSheetSize);
        }
        private void DeclareExcelApp()
        {
            m_objExcel = new Excel.ApplicationClass();
            m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
            m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
            m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
            intSheetTotalSize = GetTotalSize();
            if (intSheetTotalSize <= 3)
            {
                if (this.dbTotalSize <= this.dbSheetSize)
                {
                    this.ExportDataByQueryTable(1, false);
                    return;
                }
                else if (this.dbTotalSize <= this.dbSheetSize * 2)
                {
                    this.ExportDataByQueryTable(1, false);
                    this.ExportDataByQueryTable(2, true);
                    return;
                }
                else
                {
                    this.ExportDataByQueryTable(1, false);
                    this.ExportDataByQueryTable(2, true);
                    this.ExportDataByQueryTable(3, true);
                    return;
                }
            }
            for (int i = 3; i < intSheetTotalSize; i++)
            {
                m_objSheets.Add(m_objOpt, m_objSheets.get_Item(i), m_objOpt, m_objOpt);
            }
            ExportDataByQueryTable(1, false);
            for (int i = 2; i <= m_objSheets.Count; i++)
            {
                ExportDataByQueryTable(i, true);
            }
        }
        private void SaveExcelApp()
        {
            string excelFileName = string.Empty;
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "*.xls|*.*";
            if (sf.ShowDialog() == DialogResult.OK)
            {
                excelFileName = sf.FileName;
            }
            else
            {
                return;
            }
            m_objBook.SaveAs(excelFileName, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
                Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
        }
        private void ExportDataByQueryTable(int intSheetNumber, bool blIsMoreThan)
        {
            string strQuery = string.Empty;
            if (blIsMoreThan)
            {
                strQuery = "Select Top " +
                this.dbSheetSize + " * From PD_WORKBIL_MST Where Not  CMPID In (Select Top " +
                dbSheetSize * (intSheetNumber-1) + "  CMPID From PD_WORKBIL_MST)";
            }
            else
            {
                strQuery = "Select Top " + this.dbSheetSize + " * From PD_WORKBIL_MST ";

            }
            m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(intSheetNumber));
            m_objSheet.Cells[1,1] = "中文測試一";
            m_objSheet.Cells[1,2] = "中文測試二";
            m_objSheet.Cells[1,3] = "中文測試三";
            m_objSheet.Cells[1,4] = "中文測試四";
            m_objSheet.Cells[1,5] = "中文測試五";
            m_objRange = m_objSheet.get_Range("A2", m_objOpt);
            m_objQryTable = m_objSheet.QueryTables.Add("OLEDB;Provider=SQLOLEDB.1;" + strConnect, m_objRange, strQuery);
            m_objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;
            m_objQryTable.FieldNames = false;
            m_objQryTable.Refresh(false);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DeclareExcelApp();
            SaveExcelApp();

        }

    }
}
在本篇中﹐是將13萬多條記錄分多個Sheet導出。如果你的機器大概像我這樣:P4CPU,1G內存的話。全部導出包括保存也就是20秒左右就可以全部搞定。
也許大家會有更好的方法來實現﹐歡迎各位交流﹗

时间: 2024-11-08 19:26:10

C#導出Excel源碼的相关文章

再现C#导出Excel源码

excel|导出excel 接我上一篇C#導出Excel源碼.网上反应比较强烈.本人也因为工作需要的原因,将其封装了成了ExcelManager.企业当中,做报表的数据来源肯定就是数据库了.该ExcelManager目前只提供Ms Sql Server的支持,因为我们公司使用的就是ms sql server 2000 了.封装后的ExcelManager,你只需传入你的报表表头(一级表头.二级表头.大部分有两级也就够了.如果你有多个,可自行修改该类.),并将对应的数据库表字段传入类库中的方法De

請問怎麼才能將GRIDVIEW中的數據導到EXCEL並由用戶選擇路徑存入客戶端,並在字符型或所有字段值前加入單引號?

问题描述 求救:我現在用C#寫了幾段代碼都無法解決這個問題!如果用數據流存儲,會出現如果字符串類型的數據導入EXCEL前面的001會直接變為1而用EXCEL存儲,不會有存儲框提示,自動存在了WEB服務器上,也沒任何提示!如何才能讓用戶選擇性存儲到客戶端?多謝方式一:文件流形式(但不能解決0開台的字串問題)protectedvoidGridViewToExcel(GridViewGdv,stringstitle){Response.Clear();Response.Buffer=true;Resp

導入導出大全(2004-12-13)

導入導出大全(2004-12-13) http://builderman.home.sunbo.net/show_hdr.php?xname=U53DTV0&dname=517DTV0&xpos=1   一.打開另外一個數據庫 1. 打開SQL server2000的另一個數據庫的表 (1).  select * from openrowset('sqloledb','sprogram';'develop';'11111','select * from kind') (2).  selec

75 套頂尖的開放源碼安全防禦應用 – Part I

原文地址: http://nicaliu.info/2010/04/14/2841/   譯者:Nica < nicaliu at gmail dot com > . 建議參考:26 套提供付費技術支援的開放源碼安全防禦應用 與 2008:75 套頂尖開放源碼安全防禦應用 . FBI 指出,2009 年電腦犯罪率成長了 20%.造成 5億5仟9百萬的損失,遠超過過去兩年的總合. 隨著線上犯罪日益增長,系統防護的任務也就更加重要了.其實你不需要在安全性防護上花太多錢:開放源碼社群不斷製造與持續維

c#outlook樣式源碼,希望對對來的有所幫助

问题描述 不能上傳,我就把源碼貼出來吧,選下載一個DotNetBar.dll,拉一個sidebar控件,主要讀取菜單然後放到sidebar控件,研究了一天-但是現在不能綁定菜單事件,希望高手來改寫一下,使之能綁定菜單的click事件privatevoidInitMenu(){intpicii=10;DevComponents.DotNetBar.BaseItem[]baseitem=newDevComponents.DotNetBar.BaseItem[menuStrip1.Items.Coun

快速找出Excel中错误的身份证信息

作为办公人员,经常要编写关于职工信息档案的表格,其中最常输入的数据就是身份证号码,由于人员众多,输入确实麻烦,一不小心就可能把员工的出生日期弄错了,这可是关系到每个员工的切身利益,如工龄.社会保险金等.要是逐一验证那可是一件让人头疼的事情.下面笔者就教大家一招,通过此方法就能够很快查找出Excel表中错误的身份证号码.下面以"XXX公司员工信息统计表"为例. 首先从B列的身份证号码(注:输入前必须将该列单元格格式统一为"文本")中提取出生日期到C列,以C3为例,选中

教你用有效性圈出Excel表格中的指定数据

教你用有效性圈出Excel表格中的指定数据: 考试后老师可能会想把Excel表格中高分用红圈突出显示出来,公司统计时也许也想把特别的数据突出显示出来.这样的要求用Excel的数据有效性就能够轻松完成.下面我以成绩表为例讲解一下如何实现这一要求.(注:本例要求把语文成绩在120分以上的用红圈突出显示.) 屏显操作步骤: 第一步:打开成绩表→选择语文成绩→单击菜单栏上的"数据"按钮→选择"有效性". 第二步:在弹出的"数据有效性"对话框中,在&quo

ackage nstaller-Android 关于PackageInstaller,如何阻止弹出“未知源”对话框的问题

问题描述 Android 关于PackageInstaller,如何阻止弹出"未知源"对话框的问题 每次从应用商城下载应用时,都会弹出"为了安全,禁止未知源"的选项,我想把他去掉.看了一下代码,PackageInstallerActivity.java中,如何判断调进来的为应用商城呢?(我做的目的是应用商城不弹,其他应用调用PackageInstallerActivity弹),请教各路大神.我尝试了下面几种方法,都完败1.通过getCallingPackage(),

net office-net调用office组件,弹出 Excel已经停止工作,求解决方法!

问题描述 net调用office组件,弹出 Excel已经停止工作,求解决方法! 在读取Excel的时候,在遍历单元格的时候,弹出Excel停止工作的对话框,点击对话框中关闭程序的时候,程序跳到catch中捕捉到异常,出错的代码,是在遍历列的时候出错的,求解决方法!!! 解决方案 如果只是读数据可以使用OLBC来读,也就是将excel看做access,这样比较快 解决方案二: 遍历的方法对吗,是不是有判断获取的元素是否为空等 解决方案三: 我这里要写数据,对于同一个文件,用只读的方式打开的时候,