.net如何更快的将数据导入Excel(转帖+亲自实践)

这篇文章将介绍3种方式将数据导入Excel:

1、基本方法:一格一格地拷贝

2、使用文件流StreamWriter对象:将流写入文件

3、拷贝对象的方法:将数据复制到数组,然后直接粘贴到Excel的workbook。


基本方法

使用基本的拷贝方法将会花费大量的时间。使用文件文件流或者拷贝对象的方法将比基本方法快很多。

你必须添加一个Excel COM Object 的引用到你的应用程序之中。我将要声明两个对象,Ex为Excel.Application类型。Ws为Excel.Worksheet类型 ,然后设置Ws为workbook的第一个worksheet。

我们将写代码去循环Table每一列的标题来显示标题。

我们使用列(索引),去要检索列的标题,Caption或者ColumnName属性。 

对于全部的数据,我们将要使用两个循环,一个循环row,另外一个循环column

            Microsoft.Office.Interop.Excel.Application Ex = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Worksheet Ws ;
            Ex.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Ws= (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[1];

            int Row = 0;
            int Col = 0;
            int i = 0;
            int j = 0;
            pb.Maximum = Ds.Tables[0].Rows.Count;
            Row = 1;
            Col = 1;

            //'For Heading
            lblCount.Text = "Generating Heading.";
            this.Refresh();
            for (i = 0; i <= Ds.Tables[0].Columns.Count - 1; i++)
            {
                Ws.Cells[Row, Col] = Ds.Tables[0].Columns[i].Caption;
                Col += 1;
            }
            Row = 2;
            Col = 1;
            pb1.Maximum = Ds.Tables[0].Columns.Count;
            lblCount.Text = "Preparing for Export Data.";
            for (i = 0; i <= Ds.Tables[0].Rows.Count - 1; i++)
            {
                //
                //FOR ALL DATA
                //

                pb1.Value = 0;
                for (j = 0; j <= Ds.Tables[0].Columns.Count - 1; j++)
                {
                    Ws.Cells[Row, Col] = Ds.Tables[0].Rows[i][j].ToString();
                    Col += 1;
                    pb1.Value += 1;
                }
                //'If data is more than 65500 then set ws to next sheet
                if (Row == 65500)
                {
                    Row = 1;
                    Ws = (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[2];
                }

                Col = 1;
                Row += 1;
                lblCount.Text = i + 1 + " : Exported";
                lblCount.Refresh();
                pb.Value += 1;
            }
            pb.Value = 0;
            Ex.Visible = true;
            MessageBox.Show(Ds.Tables[0].Rows.Count + " : Records Exported. ");
            Ex.Visible = true;
            Ex.Quit();
            Ex = null;
            Ws = null;



使用StreamWriter:

这个方法比较简短而且是将数据导入如何类型的文件一种比较快方式

在这个方法中,我将使用 System.IO 命名空间,我将编程去指定的.xls 或者 .doc等扩展来直接创建一个的文件路径。

编码以文件的路径开始,这个路径是Excel文件被创建和数据存储的地方。现在,声明一个指定了路径的IO.StreamWriter对象。在这种方法中,每行的行值/列值被添加到以“|”作为分隔符的字符串中。现在,创建的文件包含以 "|" 分割的单列数据(CSV格式)。

string filePath = "c:\\SystemIO_Exported_Data_AsOn_" + DateTime.Now.ToShortDateString() + ".xls";

            //Stream Writer object to write the stream to file
           StreamWriter writer = new StreamWriter(File.Create(filePath));
       
            string str = string.Empty;

            //'For Heading
            lblCount.Text = "Generating Heading.";
            this.Refresh();
            for (int i = 0; i <= Ds.Tables[0].Columns.Count - 1; i++)
            {
                str += Ds.Tables[0].Columns[i].Caption +Constants.vbTab;
            }
            //Write stream to file adding a new line to stream
            str += Microsoft.VisualBasic.Constants.vbNewLine;
            writer.Write(str);
            writer.Flush();
            pb.Maximum = Ds.Tables[0].Rows.Count + 1;
            foreach (DataRow dRow in Ds.Tables[0].Rows)
            {

                str = "";
                for (int col = 0; col <= Ds.Tables[0].Columns.Count - 1; col++)
                {
                    string STR1 = "";
                    char c = Strings.Chr(32);
                    //char[] sep = " ";
                    string[] str2 = null;
                    str2 = dRow[col].ToString().Split(' ');
                    for (int z = 0; z <= str2.Length - 1; z++)
                    {
                        //replacing all spaces and tabs with '|' (pipe sign)
                        string y = str2[z].ToString().Replace(Strings.Chr(32), ' ').Replace(Strings.Chr(13), ' ').Replace(Strings.Chr(10), ' ').Replace(Strings.Chr(9), ' ').Replace("|", " ");
                        STR1 += y + " ";
                    }
                    str += STR1 + "| ";
                    pb.Value += 1;
                }
                str += Constants.vbNewLine;
                writer.Write(str);
                writer.Flush();
                pb.Value = 0;
            }
            //Close the stream writer object
            writer.Close();
            pb.Value = 0;
            MessageBox.Show("Data Exported Successfully.");



对象拷贝的方法:

这是另外一中将数据导入Excel的方法。

在代码中,我们创建了二维数组:object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count]来包含数据表中的数据

一旦数据被存储在一个数组当中,它将通过Excel Worksheet 的get_Range().value方法 ,将数据粘贴到一个 excel worksheet 之中。

           Microsoft.Office.Interop.Excel.Application Ex = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Worksheet Ws;
            Microsoft.Office.Interop.Excel.Workbook Wb = Ex.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Ws = (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[1];

            // Copy each DataTable as a new Sheet
            foreach (System.Data.DataTable dt in Ds.Tables)
            {
                //On Error Resume Next
                int col = 0;
                int row = 0;
                // Copy the DataTable to an object array
                object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
                lblCount.Text = "Copying Columns Name.";
                this.Refresh();
                // Copy the column names to the first row of the object array
                pb1.Maximum = dt.Columns.Count + 1;
                pb1.Value = 0;
                for (col = 0; col <= dt.Columns.Count - 1; col++)
                {
                    rawData[0, col] = dt.Columns[col].ColumnName.ToUpper();
                    pb1.Value += 1;
                }
                lblCount.Text = "Copying Data";
                this.Refresh();
                pb1.Value = 0;
                // Copy the values to the object array
                pb.Maximum = dt.Rows.Count + 1;
                pb.Value = 0;
                for (col = 0; col <= dt.Columns.Count - 1; col++)
                {
                    for (row = 0; row <= dt.Rows.Count - 1; row++)
                    {
                        rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                        pb.Value += 1;
                    }
                    pb.Value = 0;
                    pb1.Value += 1;
                }
                pb.Value = 0;
                pb1.Value = 0;
                lblCount.Text = "";
                this.Refresh();
                // Calculate the final column letter
                string finalColLetter = string.Empty;
                finalColLetter = ExcelColName(dt.Columns.Count);
                //Generate Excel Column Name (Column ID)


                sheetIndex += 1;
                Ws = (Microsoft.Office.Interop.Excel.Worksheet)Wb.Worksheets[sheetIndex];
                Ws.Name = dt.TableName;
                //指定输出的位置
                string excelRange = string.Format( "{0}{1}:{2}{3}","yr","4", "yt", dt.Rows.Count + 1);


                Ws.get_Range(excelRange, Type.Missing).Value2  = rawData;

               //注:此处的get_Range()方法,在vb.net2008中出错,显示没有定义该方法

              //可以改为Ws.Range(excelRange).Value2=rawData;即可正常使用
                Ws = null;
            }

            Wb.SaveAs("C:\\ExportedDataUsingObjectPastingMethod.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
            Wb.Close(true, Type.Missing, Type.Missing);
            Wb = null;
            // Release the Application object
            Ex.Quit();
            Ex = null;
            // Collect the unreferenced objects
            GC.Collect();
            Interaction.MsgBox("Exported Successfully.", MsgBoxStyle.Information,"提示");


我使用一个函数去找excel worksheet的列名
        public string ExcelColName(int Col)
        {
            if (Col < 0 & Col > 256)
            {
                Interaction.MsgBox("Invalid Argument", MsgBoxStyle.Critical,"提示");
                return null;
            }
            int i ;
            int  r;
            string S = null;
            if (Col <= 26)
            {
                S = Strings.Chr(Col + 64).ToString();
            }
            else
            {
                r = (int)(Col % 26);
                i = (int)System.Math.Floor((decimal)(Col / 26));
                if (r == 0)
                {
                    r = 26;
                    i = i - 1;
                }
                S = (Strings.Chr(i + 64) + Strings.Chr(r + 64)).ToString();
            }
            return S;
        }

 

代码:

http://files.cnblogs.com/zhuqil/ExportDataInExcel.rar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值