[转] 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导出Excel数据的方法。将导出文件存储到服务器并提供地址给客户端下载,或重定向到文件下载页面:当 Response时,数据列以 "\t" 分隔,行以"\n"分隔。好了,现在给大家展示这是怎么做的。
使用代码导出
方案1:导出全部HTML 数据到 Excel
这种方法是将Html中的所有文档内容,包括按钮,表格,图片等所有页面内容导出为 Excel
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.
Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = ""application/ms-excel";
this.EnableViewState = false;
这里我们使用了Page的"ContentType" 属性,它默认为"text/Html",输出到客户端即为Html。如果我们将它改为"ms-excel",页面将输出Excel格式的内容,客户端就可以下载并存储它了。
页面property 还包括:image/JPEG, text/HTML, image/GIF and vnd.ms-excel/msword.
方案2:从DataGrid导出数据到Excel
尽管上面的方法能帮你导出Excel数据,但它导出了所有的HTML内容,包括按钮、图片等,这并不是我们所需要的。通常,我们仅仅需要导出DataGrid中的数据。
System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1 (you created in the windowForm)
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";
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();
如果你有多个包含DataGrid 并需导出数据的页面,我们可以封装方法:
public void DGToExcel(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.UTF8;
HttpContext.Current.Response.ContentType ="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();
}
调用方法:DGToExcel(datagrid1);
方案3:自动导出Excel数据
使用此方法,你需要 下载免费的.NET组件 ,并使用如下代码(部分)导出数据:
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\Database\demo.mdb"; System.Data.OleDb.OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand();
oleDbCommand1.CommandText = "select * from parts";
oleDbCommand1.Connection = oleDbConnection1; System.Data.OleDb.OleDbCommand oleDbCommand2 = new System.Data.OleDb.OleDbCommand();
oleDbCommand2.CommandText = "select * from country";
oleDbCommand2.Connection = oleDbConnection1; Spire.DataExport.Delegates.DataParamsEventHandler(this.cellExport3_GetDataParams); oleDbConnection1.Open();
try
{
cellExport3.SaveToFile();
}
finally
{
oleDbConnection1.Close();
}
} private void cellExport3_GetDataParams
(object sender, Spire.DataExport.EventArgs.DataParamsEventArgs e)
{
if ((e.Sheet == 0) && (e.Col == 6))
{
e.FormatText = (sender as Spire.DataExport.XLS.WorkSheet).ExportCell.DataFormats.Currency;
}
}
执行上面的代码,你将得到:

此方案导出的Excel文件可以直接在Excel 2010 中打开、编辑和修改。虽然一些特定的功能不可用,但它能够被Excel 2010使用。
方案4:从DataSet导出Excel数据
依照上面都的方法,我么能很容易的导出DataSet数据到Excel,我们只需要在页面Response 时将DataSet 表中的数据组装为"ms-excel" 格式的数据,并通过Http发送出去。
注:ds 代表Dataset,用它来填充DataTable,文件名包含后缀,例如:excel2006.xls。
public void CreateExcel(DataSet ds,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
resp.AppendHeader("Content-Disposition", "attachment;filename="+FileName);
string colHeaders= "", ls_item="";
// Define table object and row object,
// and at the same time use DataSet initialize value.
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select();//dt.Select("id>10")
Data Filer can be used as: dt.Select("id>10")
int i=0;
int cl=dt.Columns.Count;
//Get column titles of each DataTable and divided by "t". Press "enter" after the last column title.
for(i=0;i<cl;i++) colheaders+="dt.Columns[i].Caption.ToString()+"t";"
for(i="0;i<cl;i++)" if(i="=(cl-1))//(last" +="dt.Columns[i].Caption.ToString()"
ls_item+="row[i].ToString()+"t";" />
方案5:从DataView导出Excel数据
如果你想导出不规则的行和列到Excel,你可以使用一下方法:
public void OutputExcel(DataView dv,string str)
{
//dv presents data which will be exported to Excel,
str is the name of title
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;
//
// Acquire Title
//
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;//Set title format as middle
} //
//Obtain data from table
//
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;// Set the style as middle
}
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;
// Set the style as middle
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//load a Aggregate line
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = " Aggregate ";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment
= XlHAlign.xlHAlignCenter;
//
//Set color for the selected content
//
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;//more than 50 types of color for you to choose
//
//obtain title of the whole excelsheet
//
excel.Cells[2,2] = str;
//
//Set title format for the whole excelsheet
//
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;
//
//Set fittest width
//
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();
//
//Set the tile as Cross and Middle
//
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;
//
//Draw borders
//
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;// Set left line as bold
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders
[XlBordersIndex.xlEdgeTop].Weight
= XlBorderWeight.xlThick;// Set upper line as bold
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders
[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//Set right line as bold
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders
[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//Set bottom line as bold
//
//Display effect
//
excel.Visible=true;
//xSt.Export(Server.MapPath(".")+");
xBk.SaveCopyAs(Server.MapPath(".")+"");
ds = null;
xBk.Close()
两种 WinForms 导出Excel 数据的解决方案
方案6:
SqlConnection conn=new SqlConnection
(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string downloadurl"].ToString()+DateTime.Today.ToString
("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next
().ToString()+".csv";//Store the path of downloadurl
in web.config and the format should be set as "date + 4 random number "
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter
(fs,System.Text.Encoding.GetEncoding("utf-8"));("utf-8")
sw.WriteLine("Auto number, name, age");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment;
filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";
//Set the return string is unavailable reading for client, and must be downloaded Response.WriteFile(name); //Send file string to client
Response.End(); public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[]; sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//define a new workbook
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing.
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item();
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item();
//Give the sheet a name
oSheet.Name="Sheet1"; oCells=oSheet.Cells;
//Call dumpdata process and export to Excel DumpData(dt,oCells);
//Store
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//Exit Excel and free invoking COM resource
oExcel.Quit();
GC.Collect();
KillProcess("Excel");
}
private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//get all opened progresses
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}
方案7:
protected void ExportExcel()
{
gridbind();
if(ds1==null) return; string saveFileName="";
// bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel File|*.xls";
saveDialog.FileName ="Sheet1";
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<) return; // Cancelled
//excelapp.Workbooks.Open (App.path & Progress table.xls) Excel.Application xlApp=new Excel.Application();
object missing=System.Reflection.Missing.Value; if(xlApp==null)
{
MessageBox.Show("Create Excel object failed, maybe you dont install Excel ");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[];// Get sheet1
Excel.Range range; string oldCaption=Title_label .Text.Trim ();
long totalCount=ds1.Tables[].Rows.Count;
long rowRead=;
float percent=; worksheet.Cells[,]=Title_label .Text.Trim ();
//Write text
for(int i=;i<ds1.tables[].columns.count;i++)
worksheet.cells[,i+]="ds1.Tables[0].Columns.ColumnName;" range.interior.colorindex="15;" range.font.bold="true;"
.visible="true;" r="0;r<ds1.Tables[0].Rows.Count;r++)"
i="0;i<ds1.Tables[0].Columns.Count;i++)"
worksheet.cells[r+,i+]="ds1.Tables[0].Rows[r];"
percent="((float)(100*rowRead))/totalCount;" this.caption.visible="false;"
this.caption.text=" Exporting Data [" range="(Excel.Range)worksheet.Cells
[,i+];" range.borders[excel.xlbordersindex.xlinsidehorizontal].colorindex=
"Excel.XlColorIndex.xlColorIndexAutomatic;"
range.borders[excel.xlbordersindex.xlinsidehorizontal].linestyle=
"Excel.XlLineStyle.xlContinuous;"
range.borders[excel.xlbordersindex.xlinsidehorizontal].weight=
"Excel.XlBorderWeight.xlThin;">)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex
=Excel.XlColorIndex.xlColorIndexAutomatic;
}
workbook.Close(missing,missing,missing);
xlApp.Quit();
}
方案8 (from Cipherlad):
使用DataSet 的GetXml方法,并且使用XSLT将XML转化为标准的Excel格式,你可以使用不同样式模版对应不容版本的Excel,甚至可以用于导出其它文档。
方案9 (from Sergelp):
使用 OOXML 格式的开源库:http://simpleooxml.codeplex.com/
这是一个非常便捷的库,它包含多种格式、字体、颜色订制,你也不需要安装Excel软件,你可以在服务端创建Excel,然后实现下载,如下代码所示:
Dim ms As MemoryStream = ArticleDAL.GetStreamFromDataSet()
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", strFile))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
ms.WriteTo(Response.OutputStream)
Response.End()
[转] Asp.Net 导出 Excel 数据的9种方案的更多相关文章
- Asp.Net 导出Excel数据文件
表格例子如下: <table id="tableExcel" width="100%" border="1" cellspacing= ...
- Asp.net导出Excel续章(自定义合并单元格,非Office组件)
结合上次写的导出Excel方法,这次上头要求我将列头进行一下合并 以前的效果: 改进后的效果: 在上篇文章中写到了Excel的导出方法,这次为了避免在生产环境中使用Office组件,服务器各种权限配置 ...
- asp.net导出excel示例代码
asp.net导出excel的简单方法. excel的操作,最常用的就是导出和导入. 本例使用NPOI实现. 代码:/// <summary> ); ; ...
- ASP.NET导出EXCEL类
最新ASP.NET导出EXCEL类 说明:可以导出ASP.NET页面和DATAGRID(WebControl)数据,可以导出表单头 using System;using System.Data;usi ...
- asp.net导出excel并弹出保存提示框
asp.net导出excel并弹出保存提示框 2013-07-12 | 阅:1 转:78 | 分享 腾讯空间 人人网 开心网 新浪微博 腾讯微博 搜狐空间 推荐给朋友 举报 ...
- oracle-sql脚本导出EXCEL数据
在数据库中,经常有业务人员提出需求导出数据库中的业务数据,而且是每天.每周或每月定时导出.为了方便,可将sql查询的脚本 通过下面脚本来导出EXCEL数据. 1.将查询sql脚本(AAA.sql)放到 ...
- flask使用tablib导出excel数据表
在网页中常常有导出数据的需求,尤其是一下管理类平台.在flask中要导出excel数据表,通常可以使用xlwt库,创建文件并逐行写入数据,但是使用起来总是感觉很麻烦.tablib库相对操作更加方便. ...
- .NET环境下导出Excel表格的两种方式和导入两种类型的Excel表格
一.导出Excel表格的两种方式,其中两种方式指的是导出XML数据类型的Excel(即保存的时候可以只需要修改扩展名为.xls)和真正的Excel这两种. using System; using Sy ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
随机推荐
- sip比较好的博客
http://blog.sina.com.cn/s/articlelist_1796220243_1_1.html
- linux下使用crontab定时备份MYSQL数据库的方法:
摘要 linux下使用crontab定时备份MYSQL数据库的方法: 只需按照下面3步做,一切都在你的掌控之下: 第一步:在服务器上配置备份目录代码: ------------------------ ...
- iOS开发日期处理
Foundation框架之 日期与时间 #import"ViewController.h"@interfaceViewController() { NSTimer*_timer;/ ...
- http://www.360doc.com/content/12/1014/00/7471983_241330790.shtml
http://www.360doc.com/content/12/1014/00/7471983_241330790.shtml
- idea自动生成serialVersionUID
Setting->Plugins 找到一个叫 GenerateSerialVersionUID 的插件 下载安装好,alt+insert就可以看到 默认情况下Intellij IDEA是关闭了 ...
- Centos上的屏幕保护
关闭Centos上的屏幕保护:setterm -blank 0 设置Centos上的屏幕保护为5分钟:setterm -blank 5
- docker 笔记(基本概念、快速运行、自定义镜像)
1.docker docker是一个打包应用的工具 非常强大,能把操作系统也打在包里,进行无差别部署和运行. 所以docker也被认为是建立在操作系统上的虚拟机. 2.基本概念 镜像(image) ...
- hbase 学习笔记二----shell
Hbase 是一个分布式的.面向列的开源数据库,其实现是建立在google 的bigTable 理论之上,并基于hadoop HDFS文件系统. Hbase不同于一般的关系型数据库 ...
- 【转】HashMap的工作原理
很好的文章,推荐Java的一个好网站:ImportNew HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道Hasht ...
- 【温故知新】c#异步编程模型(APM)--使用委托进行异步编程
当我们用到C#类许多耗时的函数XXX时,总会存在同名的类似BeginXXX,EndXXX这样的函数. 例如Stream抽象类的Read函数就有 public abstract int Read(byt ...