当前位置: 首页 > news >正文

超级简单:如何更快的将数据导入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注入漏洞检测。

相关文章:

  • springboot同mybatis整合
  • 博达路由器常见功能教学1
  • 阿特斯副总裁邢国强:2017年底光伏组件成本2元以下
  • python实战===使用随机的163账号发送邮件
  • CSS
  • 刚刚接触的涉及html的工具
  • Net设计模式之简单工厂模式(Simple Factory Pattern)
  • MySQL QA
  • 中文编程是否可行之验证——(一)
  • Provisioning Services 7.6 入门到精通系列之九:创建和配置目标设备
  • 基于OHCI的USB主机 —— 中断处理程序
  • ssh 连接缓慢解决方法
  • 编写优美的GTest测试案例
  • 【转】HBase架构解析
  • JavaScript正则表达式
  • hexo+github搭建个人博客
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • 【划重点】MySQL技术内幕:InnoDB存储引擎
  • 07.Android之多媒体问题
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • Docker入门(二) - Dockerfile
  • github指令
  • JavaScript中的对象个人分享
  • JavaWeb(学习笔记二)
  • October CMS - 快速入门 9 Images And Galleries
  • Promise面试题2实现异步串行执行
  • spring cloud gateway 源码解析(4)跨域问题处理
  • SpringBoot 实战 (三) | 配置文件详解
  • Terraform入门 - 1. 安装Terraform
  • Wamp集成环境 添加PHP的新版本
  • 包装类对象
  • 大主子表关联的性能优化方法
  • 读懂package.json -- 依赖管理
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 分类模型——Logistics Regression
  • 湖南卫视:中国白领因网络偷菜成当代最寂寞的人?
  • 讲清楚之javascript作用域
  • 浅谈web中前端模板引擎的使用
  • 我看到的前端
  • 最近的计划
  • 东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
  • #控制台大学课堂点名问题_课堂随机点名
  • $emit传递多个参数_PPC和MIPS指令集下二进制代码中函数参数个数的识别方法
  • (3)llvm ir转换过程
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • (附源码)ssm学生管理系统 毕业设计 141543
  • (七)Knockout 创建自定义绑定
  • (一)eclipse Dynamic web project 工程目录以及文件路径问题
  • (一)基于IDEA的JAVA基础10
  • (转)EOS中账户、钱包和密钥的关系
  • .gitattributes 文件
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .NET 8.0 发布到 IIS
  • .NET WebClient 类下载部分文件会错误?可能是解压缩的锅