• 超级简单:如何更快的将数据导入Excel


    代码:/Files/zhuqil/ExportDataInExcel.rar   

    这篇文章将介绍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 之中。

    代码
        if (Ds.Tables.Count > 3)
                {
                  MessageBox.Show(
    "There Are More than 3 data table. Data can not be exported.","提示");
                    
    return;
                }
                
    int sheetIndex = 0;
                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("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);


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

                Wb.SaveAs(
    "C:\\ExportedDataUsingObjectPastingMethod.xls", 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://www.codeproject.com/KB/vb/ExportDataToExcelFaster1.aspx



    (全文完)


    以下为广告部分

    您部署的HTTPS网站安全吗?

    如果您想看下您的网站HTTPS部署的是否安全,花1分钟时间来 myssl.com 检测以下吧。让您的HTTPS网站变得更安全!

    SSL检测评估

    快速了解HTTPS网站安全情况。

    安全评级(A+、A、A-...)、行业合规检测、证书信息查看、证书链信息以及补完、服务器套件信息、证书兼容性检测等。

    SSL证书工具

    安装部署SSL证书变得更方便。

    SSL证书内容查看、SSL证书格式转换、CSR在线生成、SSL私钥加解密、CAA检测等。

    SSL漏洞检测

    让服务器远离SSL证书漏洞侵扰

    TLS ROBOT漏洞检测、心血漏洞检测、FREAK Attack漏洞检测、SSL Poodle漏洞检测、CCS注入漏洞检测。

  • 相关阅读:
    cygwin 下配置ssh
    使用MarsEdit写博客
    bash no job control in this shell
    安装devtoolset-2:因由安装gcc 4.8而引起
    AFNetworking Property with 'retain (or strong)' attribute must be of object type
    从xib 创建 collectionViewCell
    CocoaPods 安装
    个人理解的 Https 通信流程
    cellforrowatindexpath 不执行 的原因
    do{} while(0) 的意义和用法
  • 原文地址:https://www.cnblogs.com/zhuqil/p/ExportDataInExcel.html
Copyright © 2020-2023  润新知