ASP.NET输出EXCEL表格的几种方法(总结修改)

这几天要从数据库导出EXCEL表格,就找了N钟方法,经测试,下面的方法比较的好用一点。都是经过输入DataTable而导出的。不过导出的EXCEL都不是正规的EXCEL格式,只能说是HTML格式的,导出的再导入进数据库就会出现问题了。想导入的话用EXCEL打开另存为EXCEL格式就好了

1.利用DataRow直接输出,经测试,没有乱码。
       
public bool LendOutExcel(string strFileName, DataTable
DT)
       
{
           
try
           
{
               
//清除Response缓存内容
               
HttpContext.Current.Response.Clear();
               
//缓存输出,并在完成整个响应之后将其发送
               
HttpContext.Current.Response.Buffer =
true;
               
//strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt
.htm
               
strFileName = strFileName +
".xls";
               
//设置输出流的HTPP字符集,确定字符的编码格式
               
//HttpContext.Current.Response.Charset =
"UTF-8";
               
HttpContext.Current.Response.ContentEncoding =
System.Text.Encoding.GetEncoding("GB2312");
               
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开

               
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" +
HttpUtility.UrlEncode(strFileName));
               
//Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档
               
HttpContext.Current.Response.ContentType = "application/ms-excel";

string colHeaders = "", ls_item =
"";
               
int i =
0;
               
//定义表对象与行对像,同时用DataSet对其值进行初始化
               
DataRow[] myRow =
DT.Select("");
               
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
               
for (i = 0; i < DT.Columns.Count - 1;
i++)
               
{
                   
colHeaders += DT.Columns[i].Caption.ToString() +
"\t";
               
}
               
colHeaders += DT.Columns[i].Caption.ToString() +
"\n";
               
//向HTTP输出流中写入取得的数据信息
               
HttpContext.Current.Response.Write(colHeaders);
               
//逐行处理数据

               
foreach (DataRow row in
myRow)
               
{
                   
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
                   
for (i = 0; i < DT.Columns.Count - 1;
i++)
                       
ls_item += row[i].ToString() +
"\t";
                   
ls_item += row[i].ToString() +
"\n";
                   
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   

                   
HttpContext.Current.Response.Write(ls_item);
                   
ls_item =
"";
               
}
               
//写缓冲区中的数据到HTTP头文件中
               
HttpContext.Current.Response.End();

return
true;
           
}
           
catch
           
{
               
return
false;
           
}
        }

输出为:学院活动表.xls

活动名称 活动时间 活动地点 发起人 承担人 批准人 活动概况 参与人
备注
第5次9                                             
2008-7-27 0:00:00 HBU_ 1 shenxian_ 1   jiaoren there where is a
will,there is a way ren ren ren ren people
haha,hehe,xixi
第5次8                                             
2008-7-27 0:00:00 HBU_ 2 shenxian_ 2 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次7                                             
2008-7-27 0:00:00 HBU_ 3 shenxian_ 3 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次6                                             
2008-7-27 0:00:00 HBU_ 4 shenxian_ 4 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次5                                             
2008-7-27 0:00:00 HBU_ 5 shenxian_ 5 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次9                                             
2008-7-27 0:00:00 HBU_ 1 shenxian_ 1   jiaoren there where is a
will,there is a way ren ren ren ren people
haha,hehe,xixi
第5次8                                             
2008-7-27 0:00:00 HBU_ 2 shenxian_ 2 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次7                                             
2008-7-27 0:00:00 HBU_ 3 shenxian_ 3 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次6                                             
2008-7-27 0:00:00 HBU_ 4 shenxian_ 4 xianren jiaoren there where is a will,there
is a way ren ren ren ren people
haha,hehe,xixi
第5次5                                             
2008-7-27 0:00:00 HBU_ 5 shenxian_ 5 xianren jiaoren there where is a will,there
is a way ren ren ren ren people haha,hehe,xixi

2.利用GridView输出,经测试,有的输出有乱码
       
public bool LendOutExcel(string strFileName, DataTable
DT)
       
{
           
try
           
{
               
//清除Response缓存内容
               
HttpContext.Current.Response.Clear();
               
//缓存输出,并在完成整个响应之后将其发送
               
HttpContext.Current.Response.Buffer =
true;
               
//strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt
.htm
               
strFileName = strFileName +
".xls";
               
//设置输出流的HTPP字符集,确定字符的编码格式
               
//HttpContext.Current.Response.Charset =
"UTF-8";
               
HttpContext.Current.Response.ContentEncoding =
System.Text.Encoding.GetEncoding("GB2312");
               
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开

               
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" +
HttpUtility.UrlEncode(strFileName));
               
//Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档 
               
HttpContext.Current.Response.ContentType = "application/ms-excel";

//用GridView输出
               
GridView dv = new
GridView();
               
dv.DataSource =
DT;
               
dv.DataBind();
               
try
               
{
                   
dv.Page.EnableViewState =
false;
               
}
               
catch
               
{
}
               
System.IO.StringWriter swBody = new
System.IO.StringWriter();
               
System.Web.UI.HtmlTextWriter hwBody = new
System.Web.UI.HtmlTextWriter(swBody);
               
//dv表示输出GridView,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
               
dv.RenderControl(hwBody);
               
//消除乱码特别设定,非常规方法
               
string strExcel =
"";
               
strExcel =
"";
               
strExcel +=
hwBody.InnerWriter.ToString();
               
HttpContext.Current.Response.Write(strExcel);
               
HttpContext.Current.Response.End();

return
true;
           
}
           
catch
           
{
               
return
false;
           
}
        }

输出为:工作表.xls
<div>
<table cellspacing="0" rules="all"
border="1" style="border-collapse:collapse;">
  
<tr>
    <th scope="col">课程编号</th><th
scope="col">课程名称</th><th scope="col">课序号</th><th
scope="col">任课教师</th>
  
</tr><tr>
   
<td>ASP.NET-0</td><td>ASP.NET</td><td>0</td><td>shenxian</td>
  
</tr><tr>
   
<td>VB-0</td><td>VB</td><td>0</td><td>任志波</td>
  
</tr><tr>
   
<td>操作系统-0</td><td>操作系统</td><td>0</td><td>郝杰</td>
  
</tr><tr>
   
<td>计算机网络-0</td><td>计算机网络</td><td>0</td><td>杨秀丹</td>
  
</tr><tr>
   
<td>数据库-0</td><td>数据库</td><td>0</td><td>郝杰</td>
  
</tr><tr>
   
<td>数据库应用技术-0</td><td>数据库应用技术</td><td>0</td><td>wjy</td>
  
</tr><tr>
   
<td>数据库应用技术-1</td><td>数据库应用技术</td><td>1</td><td>wjy</td>
  
</tr>
</table>
</div>

3.利用DataGrid输出,导出没问题,有没有乱码的问题没注意

protected void btnLendIn_Click(object sender, EventArgs
e)
    {
    DataTable dt =
LIE.LendInDT();
    StringWriter stringWriter = new
StringWriter();
    HtmlTextWriter htmlWriter = new
HtmlTextWriter( stringWriter );
    DataGrid excel = new
DataGrid();
    System.Web.UI.WebControls.TableItemStyle
AlternatingStyle = new TableItemStyle();
   
System.Web.UI.WebControls.TableItemStyle headerStyle = new
TableItemStyle();
    System.Web.UI.WebControls.TableItemStyle
itemStyle = new TableItemStyle();
   
AlternatingStyle.BackColor =
System.Drawing.Color.LightGray;
    headerStyle.BackColor
=System.Drawing.Color.LightGray;
    headerStyle.Font.Bold =
true;
    headerStyle.HorizontalAlign =
System.Web.UI.WebControls.HorizontalAlign.Center;
   
itemStyle.HorizontalAlign =
System.Web.UI.WebControls.HorizontalAlign.Center;;

excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
   
excel.HeaderStyle.MergeWith(headerStyle);
   
excel.ItemStyle.MergeWith(itemStyle);
    excel.GridLines =
GridLines.Both;
    excel.HeaderStyle.Font.Bold =
true;
    excel.DataSource = dt.DefaultView;   
//输出DataTable的内容
    excel.DataBind();
   
excel.RenderControl(htmlWriter);

    string filestr
="d:\\1.xls";   //filePath是文件的路径
    int pos =
filestr.LastIndexOf("\\");
    string file =
filestr.Substring(0,pos);
    if( !Directory.Exists( file )
)
    {
    
Directory.CreateDirectory(file);
    }
   
System.IO.StreamWriter sw = new StreamWriter(filestr);
   
sw.Write(stringWriter.ToString());
    sw.Close();
}

输出的内容为:1.xls
<table cellspacing="0" rules="all" border="1"
style="border-collapse:collapse;">
<tr align="center"
style="background-color:LightGrey;font-weight:bold;">
  
<td>课程编号</td><td>课程名称</td><td>课序号</td><td>任课教师</td>
</tr><tr
align="center">
  
<td>ASP.NET-0</td><td>ASP.NET</td><td>0</td><td>shenxian</td>
</tr><tr
align="center" style="background-color:LightGrey;">
  
<td>VB-0</td><td>VB</td><td>0</td><td>任老师</td>
</tr><tr
align="center">
  
<td>操作系统-0</td><td>操作系统</td><td>0</td><td>郝老师</td>
</tr><tr
align="center" style="background-color:LightGrey;">
  
<td>计算机网络-0</td><td>计算机网络</td><td>0</td><td>杨老师</td>
</tr><tr
align="center">
  
<td>数据库-0</td><td>数据库</td><td>0</td><td>郝老师</td>
</tr><tr
align="center" style="background-color:LightGrey;">
  
<td>数据库应用技术-0</td><td>数据库应用技术</td><td>0</td><td>wjy</td>
</tr><tr
align="center">
  
<td>数据库应用技术-1</td><td>数据库应用技术</td><td>1</td><td>wjy</td>
</tr>
</table>

本文转自http://hi.baidu.com/zagelover/item/f143b9118342bbe99913d675

经测试 第一种方法可行 其余方法暂时还没用到

导出excel时 如果是页面[ajax页面]中含有<asp:UpdatePanel 
和<asp:ScriptManager控件时  如果你的事件按钮在UpdatePanel 范围内会报错

解决办法就是把时间按钮放到UpdatePanel 范围之外

时间: 2024-08-26 05:46:26

ASP.NET输出EXCEL表格的几种方法(总结修改)的相关文章

C#WinForm 直接导出DataGridView数据到Excel表格的二种方法对比

方法一.利用微软的excel 操作类 引用:using Excel = Microsoft.Office.Interop.Excel; 代码如下:         #region导出数据表:Excle (微软的excel 操作类)         ///<summary>         ///导出数据表:Excle         ///</summary>         ///<param name="myDGV"></param>

如何将PDF转Excel表格?俩种方法三秒搞定

大家在日常办公中会不会遇到这类问题呢,关于如何将PDF转Excel表格的问题,前阵子有几个小伙伴给我留言问到的问题,今天正好可以这里回复一下方法,希望可以帮助到你们哟~这次发个福利,分享俩种,机会不容错过,一起看下吧!No.1复制粘贴到Excel第一步.首先我们将已准备好的PDF文件打开,并复制内容.第二步.新建一个Excel表格,将内容粘贴进去,如图所示,然后进行编辑调整成自己想要的排版.No.2直接转换格式第一步.打开一个这样的含有PDF转Excel转换功能的转换器.(这里使用的是在线转换器

[转] Asp.Net 导出 Excel 数据的9种方案

湛刚 de BLOG 原文地址 Asp.Net 导出 Excel 数据的9种方案 简介 Excel 的强大之处在于它不仅仅只能打开Excel格式的文档,它还能打开CSV格式.Tab格式.website table 等多钟格式的文档.它具备自动识别行号,字符,格式化数字等功能,例如:如果你在Excel 单元格中输入数字 "123456789012" 会自动转化为"1.23457E+11". 背景介绍 正因为Excel的强大和易用,大家都喜欢将数据导出为 Excel 备

asp.net(c#)网页跳转七种方法小结

1.response.redirect  这个跳转页面的方法跳转的速度不快,因为它要走2个来回(2次 postback),但他可以跳 转到任何页面,没 有站点页面限制(即可以由雅虎跳到新浪),同时不能跳过登录保护.但速度慢是其最大缺陷!redirect跳转机制:首先是发送一个 http请求到客户端,通知需要跳转到新页面,然后客户端在发送跳转请求到服务器端.需要注意的是跳转后内部空间保存的所有数据信息将会丢失,所以需要用到session. 实例 : using System; using Syst

asp.net跳转页面的三种方法比较

目前,对于学习asp.net的很多朋友来讲,实现跳转页面的方法还不是很了解.本文将为朋友们介绍利用asp.net跳转页面的三种方法,并对其之间的形式进行比较,希望能够对朋友们有所帮助. ASP.NET发展起源 1 ASP.NET的前身ASP技术,是在IIS 2.0上首次推出(Windows NT 3.51),当时与 ADO 1.0 一起推出,在IIS 3.0 (Windows NT 4.0)发扬光大,成为服务器端应用程序的热门开发工具,微软还特别为它量身打造了Visual InterDev开发工

php语言中Excel表格导入数据库的方法详解

在php编程语言中,对于如何在Excel表格中导入数据库的方法是很多编程者比较头疼的一个问题,有些技术人员可能在百度尝试过搜索很多不同的问题,但是给出的答案经过自己测试之后,发现还是行不通,那么对此,燚轩科技也尝试了一下如何在Excel表格中导入数据库,现在将源代码展示给各位技术编程者,大家可以借鉴参考一下. public function saveexcel(){require_once('./Thinkphp/Extend/Vendor/PHPExcel-1.8/Classes/PHPExc

利用JavaScript如何创建一个table表格[第2种方法]

创建一个五行五列的表格(使用循环) <style> td{border:1px solid #ccc;} </style> <script> window.onload=function(){ var oTable=document.createElement("table"); var row; var cell; for(var i=0;i<5;i++){ row=document.createElement("tr")

【转】Asp.net中时间格式化的6种方法详细总结

1. 数据控件绑定时格式化日期方法: 代码如下: <asp:BoundColumn DataField="AddTime" HeaderText="添加时间" DataFormatString="{0:yyyy-MM-dd HH:mm}></asp:BoundColumn> <asp:BoundField DataField="AddTime" HeaderText="添加时间" Dat

YbSoftwareFactory 代码生成插件【二十五】:Razor视图中以全局方式调用后台方法输出页面代码的三种方法

上一篇介绍了 MVC中实现动态自定义路由 的实现,本篇将介绍Razor视图中以全局方式调用后台方法输出页面代码的三种方法. 框架最新的升级实现了一个页面部件功能,其实就是通过后台方法查询数据库内容,把查询结果的 HTML 代码呈现到 Razor 视图中,考虑到灵活性,需要能在任意 Razor 视图中调用该方法,这样任意 Razor 页面都能以统一的方式方便地共享该页面部件的 HTML 内容,这对于代码的重用性和可维护性都是非常有必要的. 为实现上述要求,本文介绍如下可供选择的三种方式.   1.