另一种数据导出的方法

声明:下面的代码是从网上复制过过来的,没有找到发表人的连接,如果发表人看到此文章,请和我联系,我会把您的连接加上,以示对您的尊重。此代码未经验证。

 发表者:fmjwn

引用excel  
  public   class   exporttoexcel  
          {  
   
                  私有成员#region   私有成员  
                  //   数据的dataview  
                  private   dataview   dv=null;  
   
                  //   表格标题  
                  private   string   title=null;  
   
                  //   输出文件路径  
                  private   string   outfilepath=null;  
   
     
                  //   输入文件名  
                  private   string   inputfilepath=system.windows.forms.application.startuppath+@"   emplate.xls";  
   
                  #endregion  
   
                  公共属性#region   公共属性  
                  /**   <summary>  
                  ///   数据的dataview  
                  ///   </summary>  
                  public   dataview   dv  
                  {  
                          set  
                          {  
                                  dv=value;  
                          }  
                  }  
   
                  /**   <summary>  
                  ///   表格标题  
                  ///   </summary>  
                  public   string   title  
                  {  
                          set  
                          {  
                                  title=value;  
                          }  
                          get  
                          {  
                                  return   title;  
                          }  
                  }  
   
                  /**   <summary>  
                  ///   输出文件路径  
                  ///   </summary>  
                  public   string   outfilepath  
                  {  
                          set  
                          {  
                                  outfilepath=value;  
                          }  
                          get  
                          {  
                                  return   outfilepath;  
                          }  
                  }  
   
                  /**   <summary>  
                  ///   输入文件路径  
                  ///   </summary>  
                  private   string   inputfilepath  
                  {  
                          set  
                          {  
                                  inputfilepath=value;  
                          }  
                          get  
                          {  
                                  return   inputfilepath;  
                          }  
                  }  
   
                  #endregion                
   
                  构造函数#region   构造函数  
   
                  public   exporttoexcel()  
                  {  
                  }  
   
  //                 public   outputexcel(dataview   dv,string   title)  
  //                 {  
  //  
  //                 }  
   
                  #endregion  
   
                  公共方法#region   公共方法  
                  /**///  
                  public   void   createexcel()  
                  {  
                          int   rowindex=4;//行起始坐标  
                          int   colindex=1;//列起始坐标  
   
                          applicationclass   myapp=null;  
                          workbook   mybook=null;  
                          worksheet   mysheet=null;  
   
                          //如果文件不存在,则将模板文件拷贝一份作为输出文件  
                          if(!file.exists(outfilepath))  
                          {  
                                  file.copy(inputfilepath,outfilepath,true);  
                          }  
   
                          myapp=   new   applicationclass();  
                          myapp.visible=false;  
                          object   omissiong=system.reflection.missing.value;  
                          myapp.workbooks.open(outfilepath,omissiong,omissiong,omissiong,omissiong,  
                                  omissiong,omissiong,omissiong,omissiong,omissiong,omissiong,omissiong,  
                                  omissiong,omissiong,omissiong);  
                          mybook=myapp.workbooks[1];  
                          mysheet=(worksheet)mybook.activesheet;  
   
                          //取得标题  
                          foreach(datacolumn   col   in   dv.table.columns)  
                          {  
                                  colindex++;  
                                  mysheet.cells[4,colindex]   =   col.columnname;  
                                  mysheet.get_range(mysheet.cells[4,colindex],mysheet.cells[4,colindex]).horizontalalignment   =   xlvalign.xlvaligncenter;//设置标题格式为居中对齐  
                          }  
   
                          //取得表格中的数据  
                          foreach(datarowview   row   in   dv)  
                          {  
                                  rowindex   ++;  
                                  colindex   =   1;  
                                  foreach(datacolumn   col   in   dv.table.columns)  
                                  {  
                                          colindex   ++;  
                                          if(col.datatype   ==   system.type.gettype("system.datetime"))  
                                          {  
                                                  mysheet.cells[rowindex,colindex]   =   (convert.todatetime(row[col.columnname].tostring())).tostring("yyyy-mm-dd");  
                                                  mysheet.get_range(mysheet.cells[rowindex,colindex],mysheet.cells[rowindex,colindex]).horizontalalignment   =   xlvalign.xlvaligncenter;//设置日期型的字段格式为居中对齐  
                                          }  
                                          else     if(col.datatype   ==   system.type.gettype("system.string"))  
                                          {  
                                                  mysheet.cells[rowindex,colindex]   =   ""+row[col.columnname].tostring();  
                                                  mysheet.get_range(mysheet.cells[rowindex,colindex],mysheet.cells[rowindex,colindex]).horizontalalignment   =   xlvalign.xlvaligncenter;//设置字符型的字段格式为居中对齐  
                                          }  
                                          else  
                                          {  
                                                  mysheet.cells[rowindex,colindex]   =   row[col.columnname].tostring();  
                                          }  
                                  }  
                          }  
   
                          //加载一个合计行  
                          int   rowsum   =   rowindex   +   1;  
                          int   colsum   =   2;  
                          mysheet.cells[rowsum,2]   =   "合计";  
                          mysheet.get_range(mysheet.cells[rowsum,2],mysheet.cells[rowsum,2]).horizontalalignment   =   xlhalign.xlhaligncenter;  
   
                          //设置选中的部分的颜色  
                          mysheet.get_range(mysheet.cells[rowsum,colsum],mysheet.cells[rowsum,colindex]).select();  
                          mysheet.get_range(mysheet.cells[rowsum,colsum],mysheet.cells[rowsum,colindex]).interior.colorindex   =   19;//设置为浅黄色,共计有56种  
   
                          //取得整个报表的标题  
                          mysheet.cells[2,2]   =   title;  
   
                          //设置整个报表的标题格式  
                          mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,2]).font.bold   =   true;  
                          mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,2]).font.size   =   22;  
   
                          //设置报表表格为最适应宽度  
                          mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).select();  
                          mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).columns.autofit();  
   
                          //设置整个报表的标题为跨列居中  
                          mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,colindex]).select();  
                          mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,colindex]).horizontalalignment   =   xlhalign.xlhaligncenteracrossselection;  
   
                          //绘制边框  
                          mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).borders.linestyle   =   1;  
                          mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,2]).borders[xlbordersindex.xledgeleft].weight   =   xlborderweight.xlthick;//设置左边线加粗  
                          mysheet.get_range(mysheet.cells[4,2],mysheet.cells[4,colindex]).borders[xlbordersindex.xledge].weight   =   xlborderweight.xlthick;//设置上边线加粗  
                          mysheet.get_range(mysheet.cells[4,colindex],mysheet.cells[rowsum,colindex]).borders[xlbordersindex.xledgeright].weight   =   xlborderweight.xlthick;//设置右边线加粗  
                          mysheet.get_range(mysheet.cells[rowsum,2],mysheet.cells[rowsum,colindex]).borders[xlbordersindex.xledgebottom].weight   =   xlborderweight.xlthick;//设置下边线加粗  
                          mybook.save();  
                          mybook.close(   true,outfilepath,true);  
   
                          system.runtime.interopservices.marshal.releasecomobject(mysheet);  
                          system.runtime.interopservices.marshal.releasecomobject(mybook);  
                          system.runtime.interopservices.marshal.releasecomobject(myapp);  
   
                          myapp.quit();  
                          gc.collect();  
                  }  
                  #endregion  
   
                   
          }

发表者:tigerwen01

asp.net中数据库数据导入excel并打印  
  来源:http://www.pcdog.com/p/html/20041221/211220046190_1.htm  
  众所周知,web上的打印是比较困难的,常见的web上打印的方法大概有三种:  
   
    1、直接利用ie的打印功能。一般来说,这种方法可以做些扩展,而不是单单的调用javascript:print()这样简单,比如,可以使用如下代码:  
  <object   id=webbrowser   classid=clsid:8856f961-340a-11d0-a96b-00c04fd705a2   height=0   width=0></object><input   type=button   value=打印   οnclick=document.all.webbrowser.execwb(6,1)><inputtype=button   value=直接打印   οnclick=document.all.webbrowser.execwb(6,6)><inputtype=button   value=页面设置   οnclick=document.all.webbrowser.execwb(8,1)><input   type=button   value=打印预览   οnclick=document.all.webbrowser.execwb(7,1)>  
   
    这种方法可以适用于简单的数据打印,对系统要求不高,但不足之处在于可以控制的能力比较差,比如处理分页等问题。    
   
    2、利用水晶报表或其他第三方工具,如微软的reporting   service。水晶报表或其他第三方控件的打印,一般是导出到excel,word,pdf等再进行打印的,效果比较好,但编程比较复杂,控制起来也不大方便,而且这些工具都是要收费的。  
   
    3、将数据库的数据或要打印的内容导出到excel,word中去打印。使用这种方法,可以在服务端或者客户端进行。在服务端使用的话,要求服务端要安装word,excel,在客户端使用的话,要求客户端在ie的安全设置上有一定要求。使用这种方法,可适应性比较强,控制较好。本文将以在asp.net中使用excel为例子,介绍如何将数据导出到excel的几种方法。  
   
    首先,先介绍在服务端使用excel的方法。要在服务器端使用excel,必须要求服务器端安装excel,并且要求一定的访问权限。比如,需要添加<identity   impersonate="true"/>到web.config中。在本文中,要给予web目录可写的权限。  
   
    接下来,使用vs.net   2003新建一个vb.net的工程,并添加引用。由于我们要使用的是excel,所以添加一个关于com的应用,这里添加的是microsoft   excel   object   library,之后,添加的代码如下:  
  imports   system.runtime.interopservices.marshalimports   officeprivate   sub   page_load(byval   sender   as   system.object,   byval   e   as   system.eventargs)   handles   mybase.load 以com方式处理excel dim   oexcel   as   new   excel.application dim   obooks   as   excel.workbooks,   obook   as   excel.workbook dim   osheets   as   excel.sheets,   osheet   as   excel.worksheet dim   ocells   as   excel.range dim   sfile   as   string,   stemplate   as   string 定义一个datatable dim   dt   as   datatable   =   ctype(application.item("mydatatable"),   datatable) sfile   =   server.mappath(request.applicationpath)   &   "/myexcel.xls" 定义模版文件 stemplate   =   server.mappath(request.applicationpath)   &   "/mytemplate.xls" oexcel.visible   =   false oexcel.displayalerts   =   false 定义一个新的工作簿 obooks   =   oexcel.workbooks obooks.open(server.mappath(request.applicationpath)   &   "/mytemplate.xls")   obook   =   obooks.item(1) osheets   =   obook.worksheets osheet   =   ctype(osheets.item(1),   excel.worksheet) 命名该sheet osheet.name   =   "first   sheet" ocells   =   osheet.cells 调用dumpdata过程,将数据导入到excel中去 dumpdata(dt,   ocells) 保存 osheet.saveas(sfile) obook.close() 退出excel,并且释放调用的com资源 oexcel.quit() releasecomobject(ocells)   :   releasecomobject(osheet) releasecomobject(osheets)   :   releasecomobject(obook) releasecomobject(obooks)   :   releasecomobject(oexcel) oexcel   =   nothing   :   obooks   =   nothing   :   obook   =   nothing osheets   =   nothing   :   osheet   =   nothing   :   ocells   =   nothing system.gc.collect() response.redirect(sfile)end   sub将datatable的内容导出到excel的单元格中去   private   function   dumpdata(byval   dt   as   datatable,   byval   ocells   as   excel.range)   as   string dim   dr   as   datarow,   ary()   as   object dim   irow   as   integer,   icol   as   integer 输出列标题 for   icol   =   0   to   dt.columns.count   -   1  ocells(2,   icol   +   1)   =   dt.columns(icol).tostring next 将数据导出到相应的单元格 for   irow   =   0   to   dt.rows.count   -   1  dr   =   dt.rows.item(irow)  ary   =   dr.itemarray  for   icol   =   0   to   ubound(ary)   ocells(irow   +   3,   icol   +   1)   =   ary(icol).tostring   response.write(ary(icol).tostring   &   vbtab)  next nextend   functionend   class  
   
    在上面的代码中,首先,先定义了一些关于excel的对象,如application,workbook,sheets,sheet等,这些都是在使用excel的com对象时,必不可少的。之后,我们事先先定义了一个excel的模版文件,并且用excel先打开这个模版文件,再调用一个自定义的过程dumpdata。在这个自定义的过程中,将datatable中的数据,逐一导入到excel的单元格中去。读者自己可以慢慢体会下,上面的代码中,是如何将datatable中的数据导出到excel中去的。程序运行后,可以在当前的工作目录下,生成名为myexcel.xls的excel文件,如下图:  
     
   
  大家可能觉得上面的代码比较复杂,因为上面对于对打印要求比较高的应用,是十分有效的。如果只是单单对数据进行导出,还可以使用简单的格式,比如使用以下的代码:  
  private   sub   page_load(byval   sender   as   system.object,   byval   e   as   system.eventargs)   handles   mybase.load dim   dt   as   datatable   =   ctype(application.item("mydatatable"),   datatable) response.contenttype   =   "application/ms-excel" response.addheader("content-disposition",   "inline;filename=test.xls") response.write(convertdttotdf(dt))end   subprivate   function   convertdttotdf(byval   dt   as   datatable)   as   string dim   dr   as   datarow,   ary()   as   object,   i   as   integer dim   icol   as   integer    输出列标题 for   icol   =   0   to   dt.columns.count   -   1  response.write(dt.columns(icol).tostring   &   vbtab) next response.write(vbcrlf) 输出数据 for   each   dr   in   dt.rows  ary   =   dr.itemarray  for   i   =   0   to   ubound(ary)   response.write(ary(i).tostring   &   vbtab)  next  response.write(vbcrlf) nextend   functionend   class  
   
    在上面的代码中,首先将浏览器的输出类型设置为application/ms-excel,并设置excel的输出类型是在浏览器中输出,默认的名字为test.xls,之后,将调用自定义的过程,该自定义的过程将一个datatable里的数据以字符串流的形式输出,其中每个datatable里的数据之间以tab制表符分隔,最后再输出到浏览器,输出效果如下图:  
     
   
    上面的这种方法,表现的形式比较简单,但也可以满足数据导出的基本要求。那如果要进一步修饰一下的话,要如何做呢?这里提供一个方法,可以将要导出的数据先绑定到datagrid,然后再打印该datagrid。这时就可以对要打印出来的datagrid进行格式化,设置datagrid的format等属性。代码如下:  
  protected   overrides   sub   render(byval   writer   as   system.web.ui.htmltextwriter) dim   dt   as   datatable   =   ctype(application.item("mydatatable"),   datatable) response.contenttype   =   "application/ms-excel" response.addheader("content-disposition",   "inline;filename=test.xls") datagrid1.datasource   =   dt datagrid1.databind() datagrid1.rendercontrol(writer)end   sub  
   
    打印出来的效果如下图:  
     
   
    如果要转到word里面打印的话,也同样可以用上面的方法,只需要将其中的代码改成:  
  response.contenttype   =   "application/ms-word"response.addheader("content-disposition",   "inline;filename=test.doc")  
   
    最后,来看一下,如何调用客户端的excel进行打印,就是让客户一点击"打印"的按钮,就可以自动打开客户端的excel,将要打印的内容导入。要实现这样的效果,必须要求客户端的ie浏览器设置中,在其中的"安全-本地intranet-自定义级别中",将"下载未签名activx"中设置为启动或提示。代码如下:  
  <script   language="vbscript"> sub   exportbutton_onclick  dim   shtml,   oexcel,   obook  shtml   =   document.all.item("datagrid1").outerhtml  set   oexcel   =   createobject("excel.application")  set   obook   =   oexcel.workbooks.add  obook.htmlproject.htmlprojectitems("sheet1").text   =   shtml  obook.htmlproject.refreshdocument  oexcel.visible   =   true  oexcel.usercontrol   =   true end   sub</script>  
   
    在code-behind的代码中,只需要这样写就可以了:  
  dim   dt   as   datatable   =   ctype(application.item("mydatatable"),   datatable)datagrid1.datasource   =   dtdatagrid1.databind()  
   
    当运行程序时,用户只需要点击export   to   excel的按钮,此时ie浏览器会提示是否允许activx控件交互,则选择"是",就可以打开客户端的excel进行打印操作了。  
   
    以上是在asp.net中,常用的几种对excel进行操作的方法,各有优劣,希望大家可以根据实际情况选用。  
 

发表者:codeangel

给你一个,我用的导出类  
  ///   <summary>从datagrid导出指定类型的文件</summary>  
  ///   <summary>super   2005/8/4</summary>  
  ///   <param   name="ctl">datagrid的id</param>  
  ///   <param   name="filetype">导出文件类型//image/jpeg;text/html;image/gif;vnd.ms-excel/msword   ;//application/ms-excel</param>  
  ///   <param   name="filename">导出的文件名</param>  
  ///   <returns>文件</returns>  
  public   void   exportdatagrid(system.web.ui.control   ctl,string   filetype,   string   filename)    
  {    
  httpcontext.current.response.appendheader("content-disposition","attachment;filename="+filename);    
   
  httpcontext.current.response.charset   ="utf-8";    
  httpcontext.current.response.contentencoding    
  =system.text.encoding.default;    
  httpcontext.current.response.contenttype    
  =filetype;//image/jpeg;text/html;image/gif;vnd.ms-excel/msword   ;//application/ms-excel  
   
  ctl.page.enableviewstate   =false;    
  system.io.stringwriter   tw   =   new   system.io.stringwriter()   ;    
  system.web.ui.htmltextwriter   hw   =   new   system.web.ui.htmltextwriter    
  (tw);    
  ctl.rendercontrol(hw);    
  httpcontext.current.response.write(tw.tostring());    
  httpcontext.current.response.end();    
  }    
  usage:  
  exportdatagrid(datagrid_radio,"application/ms-excel","myfile.xls 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值