asp.net里导出excel表方法汇总

asp.net里导出excel表方法汇总

1、由dataset生成

public void CreateExcel(DataSet ds,string typeid,string FileName) 

  {

   HttpResponse resp;

   resp = Page.Response;

   resp.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312”);

   resp.AppendHeader(“Content-Disposition”, “attachment;filename=” + FileName);   

   string colHeaders= “”, ls_item=””;

   int i=0;

   //定义表对象与行对像,同时用DataSet对其值进行初始化

   DataTable dt=ds.Tables[0];

   DataRow[] myRow=dt.Select(“”); 

   // typeid==”1″时导出为EXCEL格式文件;typeid==”2″时导出为XML格式文件

   if(typeid==”1″)

   {

    //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符

    for(i=0;i     colHeaders+=dt.Columns[i].Caption.ToString()+”\t”;

    colHeaders +=dt.Columns[i].Caption.ToString() +”\n”;   

    //向HTTP输出流中写入取得的数据信息

    resp.Write(colHeaders); 

    //逐行处理数据  

    foreach(DataRow row in myRow)

    {

     //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n

     for(i=0;i      ls_item +=row[i].ToString() + “\t”;     

     ls_item += row[i].ToString() +”\n”;

     //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据    

     resp.Write(ls_item);

     ls_item=””;

    }

   }

   else

   {

    if(typeid==”2″)

    { 

     //从DataSet中直接导出XML数据并且写到HTTP输出流中

     resp.Write(ds.GetXml());

    }    

   }

   //写缓冲区中的数据到HTTP头文件中

   resp.End();

  }

 

2、使用微软的C++写的ACTIVEX控件:http://download.microsoft.com/download/OfficeXPDev/sample/1.0/WIN98MeXP/EN-US/Dsoframerctl.exe

3、由datagrid生成:

public void ToExcel(System.Web.UI.Control ctl)  

  {

   HttpContext.Current.Response.AppendHeader(“Content-Disposition”,”attachment;filename=Excel.xls”);

   HttpContext.Current.Response.Charset =”UTF-8″;    

   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;

   HttpContext.Current.Response.ContentType =”application/ms-excel”;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword

   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();

  }

用法:ToExcel(datagrid1);

4、这个用dataview ,代码好长

public void OutputExcel(DataView dv,string str)

{

   //

   // TODO: 在此处添加构造函数逻辑

   //

                           //dv为要输出到Excel的数据,str为标题名称

   GC.Collect();

   Application excel;// = new Application();

   int rowIndex=4;

   int colIndex=1;

   _Workbook xBk;

   _Worksheet xSt;

   excel= new ApplicationClass();

  

   xBk = excel.Workbooks.Add(true);

   

   xSt = (_Worksheet)xBk.ActiveSheet;

   //

   //取得标题

   //

   foreach(DataColumn col in dv.Table.Columns)

   {

    colIndex++;

    excel.Cells[4,colIndex] = col.ColumnName;

    xSt.get_Range(excel.Cells[4,colIndex],excel.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”))

     {

      excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString(“yyyy-MM-dd”);

      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐

     }

     else

      if(col.DataType == System.Type.GetType(“System.String”))

     {

      excel.Cells[rowIndex,colIndex] = “’”+row[col.ColumnName].ToString();

      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐

     }

     else

     {

      excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();

     }

    }

   }

   //

   //加载一个合计行

   //

   int rowSum = rowIndex + 1;

   int colSum = 2;

   excel.Cells[rowSum,2] = “合计”;

   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;

   //

   //设置选中的部分的颜色

   //

   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();

   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种

   //

   //取得整个报表的标题

   //

   excel.Cells[2,2] = str;

   //

   //设置整个报表的标题格式

   //

   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;

   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;

   //

   //设置报表表格为最适应宽度

   //

   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();

   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();

   //

   //设置整个报表的标题为跨列居中

   //

   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();

   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;

   //

   //绘制边框

   //

   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;

   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗

   xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗

   xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗

   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗

   //

   //显示效果

   //

   excel.Visible=true;

   //xSt.Export(Server.MapPath(“.”)+”\\”+this.xlfile.Text+”.xls”,SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);

   xBk.SaveCopyAs(Server.MapPath(“.”)+”\\”+this.xlfile.Text+”.xls”);

   ds = null;

            xBk.Close(false, null,null);

   

            excel.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);

            xBk = null;

            excel = null;

   xSt = null;

            GC.Collect();

   string path = Server.MapPath(this.xlfile.Text+”.xls”);

   System.IO.FileInfo file = new System.IO.FileInfo(path);

   Response.Clear();

   Response.Charset=”GB2312″;

   Response.ContentEncoding=System.Text.Encoding.UTF8;

   // 添加头信息,为”文件下载/另存为”对话框指定默认文件名

   Response.AddHeader(“Content-Disposition”, “attachment; filename=” + Server.UrlEncode(file.Name));

   // 添加头信息,指定文件大小,让浏览器能够显示下载进度

   Response.AddHeader(“Content-Length”, file.Length.ToString());

   

   // 指定返回的是一个不能被客户端读取的流,必须被下载

   Response.ContentType = “application/ms-excel”;

   

   // 把文件流发送到客户端

   Response.WriteFile(file.FullName);

   // 停止页面的执行

  

   Response.End();

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/111161.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 服务器做矿机使用_文件服务器搭建

    服务器做矿机使用_文件服务器搭建云服务器搭建矿机内容精选换一换在专属主机资源上创建云服务器失败,可能由以下原因造成:您所选择的云服务器规格不在您已有的专属主机支持范围内。各类型专属主机支持的云服务器规格请参见概述。各类型专属主机支持的云服务器规格请参见概述。您的专属主机资源不足,无法创建您所选择的云服务器规格。您可以查看专属主机的剩余vCPU和内存数量是否满足您所选择的云服务器规格。如果资源不足,您弹性云服务器(Elastic…

    2022年9月30日
    0
  • MySQL字符与数字转换_MySQL字符与数字间的转换「建议收藏」

    MySQL字符与数字转换_MySQL字符与数字间的转换「建议收藏」MYSQL字符数字转换1.将字符的数字转成数字,比如’0’转成0可以直接用加法来实现例如:将pony表中的d进行排序,可d的定义为varchar,可以这样解决select*fromponyorderby(d+0)2.在进行ifnull处理时,比如ifnull(a/b,’0′)这样就会导致a/b成了字符串,因此需要把’0’改成0,即可解决此困扰。3.比较数字和varchar…

    2022年5月30日
    79
  • 测试用例_测试用例编写

    测试用例_测试用例编写1. 测试用例的概念和作用1.1. 引言对一个测试工程师来说,测试用例的设计编写是一项必须掌握的能力,但有效的设计和熟练的编写测试用例却是一个十分复杂的技术,测试用例编写者不仅

    2022年8月5日
    4
  • UART接口简介_uart接口速度

    UART接口简介_uart接口速度UART即通用异步收发传输器(UniversalAsynchronousReceiver/Transmitter),它是一种串行通信的物理接口形式。它将要传输的资料在串行通信与并行通信之间加以转换。作为把并行输入信号转成串行输出信号的芯片,UART通常被集成于其他通讯接口的连结上。一、UART硬件连接UART有4个pin(VCC,GND,RX,TX),用的TTL电平,低电平为0(0V),高电平为1(3.3V或以上)。如下图:引脚介绍:…

    2022年9月14日
    0
  • JAVA中StringBuilder学习

    JAVA中StringBuilder学习StringBuilder概述StringBuilder是一个可变的字符串类,我们可以把它看成是一个容器。作用:提高字符串的操作效率。通过代码可以说明publicclassDemo1StringBuilder{publicstaticvoidmain(String[]args){longstart=System.currentTimeMillis();StringBuildersb=newStringBuilder();

    2022年7月17日
    14
  • python3.7安装步骤_centos运行python脚本

    python3.7安装步骤_centos运行python脚本centos7自带版本是python2.7如果要用的3.0以上的版本需要手动安装,下载地址:https://www.python.org/ftp/python/1、先查看系统python的位置在哪儿whereispythonpython2.7默认安装是在/usr/bin目录中,切换到/usr/bin/cd/usr/bin/llpython*从下面的图中我们可以看到,python指向的是python2,python2指向的是python2.7,因此我们可以装个..

    2022年9月25日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号