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

本文介绍了几种在ASP.NET中实现Excel导出的方法,包括使用DataSet、DataGrid和DataView等不同数据源来生成Excel文件的技术。同时还提供了一些实用代码示例。
None.gif
None.gif
1、由dataset生成
None.gif
None.gif
public void CreateExcel(DataSet ds,string typeid,string FileName)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gifHttpResponse resp;
InBlock.gifresp 
= Page.Response;
InBlock.gifresp.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
InBlock.gifresp.AppendHeader(
"Content-Disposition""attachment;filename=" + FileName);
InBlock.gif
string colHeaders= "", ls_item="";
InBlock.gif
int i=0;
InBlock.gif
InBlock.gif
//定义表对象与行对像,同时用DataSet对其值进行初始化
InBlock.gif
DataTable dt=ds.Tables[0];
InBlock.gifDataRow[] myRow
=dt.Select("");
InBlock.gif
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
InBlock.gif
if(typeid=="1")
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
InBlock.gif
for(i=0;i colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
InBlock.gifcolHeaders 
+=dt.Columns[i].Caption.ToString() +"\n";
InBlock.gif
//向HTTP输出流中写入取得的数据信息
InBlock.gif
resp.Write(colHeaders);
InBlock.gif
//逐行处理数据
InBlock.gif
foreach(DataRow row in myRow)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
InBlock.gif
for(i=0;i ls_item +=row[i].ToString() + "\t";
InBlock.gifls_item 
+= row[i].ToString() +"\n";
InBlock.gif
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
InBlock.gif
resp.Write(ls_item);
InBlock.gifls_item
="";
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

InBlock.gif
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
if(typeid=="2")
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
//从DataSet中直接导出XML数据并且写到HTTP输出流中
InBlock.gif
resp.Write(ds.GetXml());
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

InBlock.gif
//写缓冲区中的数据到HTTP头文件中
InBlock.gif
resp.End();
InBlock.gif
InBlock.gif
ExpandedBlockEnd.gif}

None.gif
2、由datagrid生成
None.gif
None.gif
public void ToExcel(System.Web.UI.Control ctl)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gifHttpContext.Current.Response.AppendHeader(
"Content-Disposition","attachment;filename=Excel.xls");
InBlock.gifHttpContext.Current.Response.Charset 
="UTF-8";
InBlock.gifHttpContext.Current.Response.ContentEncoding 
=System.Text.Encoding.Default;
InBlock.gifHttpContext.Current.Response.ContentType 
="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
InBlock.gif
ctl.Page.EnableViewState =false;
InBlock.gifSystem.IO.StringWriter tw 
= new System.IO.StringWriter() ;
InBlock.gifSystem.Web.UI.HtmlTextWriter hw 
= new System.Web.UI.HtmlTextWriter (tw);
InBlock.gifctl.RenderControl(hw);
InBlock.gifHttpContext.Current.Response.Write(tw.ToString());
InBlock.gifHttpContext.Current.Response.End();
ExpandedBlockEnd.gif}

None.gif
None.gif用法:ToExcel(datagrid1);
None.gif
None.gif
None.gif
3、这个用dataview
None.gif
None.gif
public void OutputExcel(DataView dv,string str)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif
//
InBlock.gif
// TODO: 在此处添加构造函数逻辑
InBlock.gif
//
InBlock.gif
//dv为要输出到Excel的数据,str为标题名称
InBlock.gif
GC.Collect();
InBlock.gifApplication excel;
// = new Application();
InBlock.gif
int rowIndex=4;
InBlock.gif
int colIndex=1;
InBlock.gif
InBlock.gif_Workbook xBk;
InBlock.gif_Worksheet xSt;
InBlock.gif
InBlock.gifexcel
= new ApplicationClass();
InBlock.gif
InBlock.gifxBk 
= excel.Workbooks.Add(true);
InBlock.gif
InBlock.gifxSt 
= (_Worksheet)xBk.ActiveSheet;
InBlock.gif
InBlock.gif
//
InBlock.gif
//取得标题
InBlock.gif
//
InBlock.gif
foreach(DataColumn col in dv.Table.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifcolIndex
++;
InBlock.gifexcel.Cells[
4,colIndex] = col.ColumnName;
InBlock.gifxSt.get_Range(excel.Cells[
4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
ExpandedSubBlockEnd.gif
}

InBlock.gif
InBlock.gif
//
InBlock.gif
//取得表格中的数据
InBlock.gif
//
InBlock.gif
foreach(DataRowView row in dv)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifrowIndex 
++;
InBlock.gifcolIndex 
= 1;
InBlock.gif
foreach(DataColumn col in dv.Table.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifcolIndex 
++;
InBlock.gif
if(col.DataType == System.Type.GetType("System.DateTime"))
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifexcel.Cells[rowIndex,colIndex] 
= (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
InBlock.gifxSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment 
= XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
ExpandedSubBlockEnd.gif
}

InBlock.gif
else
InBlock.gif
if(col.DataType == System.Type.GetType("System.String"))
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifexcel.Cells[rowIndex,colIndex] 
= "'"+row[col.ColumnName].ToString();
InBlock.gifxSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment 
= XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
ExpandedSubBlockEnd.gif
}

InBlock.gif
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifexcel.Cells[rowIndex,colIndex] 
= row[col.ColumnName].ToString();
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

InBlock.gif
//
InBlock.gif
//加载一个合计行
InBlock.gif
//
InBlock.gif
int rowSum = rowIndex + 1;
InBlock.gif
int colSum = 2;
InBlock.gifexcel.Cells[rowSum,
2= "合计";
InBlock.gifxSt.get_Range(excel.Cells[rowSum,
2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
InBlock.gif
//
InBlock.gif
//设置选中的部分的颜色
InBlock.gif
//
InBlock.gif
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
InBlock.gifxSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex 
= 19;//设置为浅黄色,共计有56种
InBlock.gif
//
InBlock.gif
//取得整个报表的标题
InBlock.gif
//
InBlock.gif
excel.Cells[2,2= str;
InBlock.gif
//
InBlock.gif
//设置整个报表的标题格式
InBlock.gif
//
InBlock.gif
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
InBlock.gifxSt.get_Range(excel.Cells[
2,2],excel.Cells[2,2]).Font.Size = 22;
InBlock.gif
//
InBlock.gif
//设置报表表格为最适应宽度
InBlock.gif
//
InBlock.gif
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
InBlock.gifxSt.get_Range(excel.Cells[
4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
InBlock.gif
//
InBlock.gif
//设置整个报表的标题为跨列居中
InBlock.gif
//
InBlock.gif
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
InBlock.gifxSt.get_Range(excel.Cells[
2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
InBlock.gif
//
InBlock.gif
//绘制边框
InBlock.gif
//
InBlock.gif
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
InBlock.gifxSt.get_Range(excel.Cells[
4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
InBlock.gif
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
InBlock.gif
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
InBlock.gif
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
InBlock.gif
//
InBlock.gif
//显示效果
InBlock.gif
//
InBlock.gif
excel.Visible=true;
InBlock.gif
InBlock.gif
//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
InBlock.gif
xBk.SaveCopyAs(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls");
InBlock.gif
InBlock.gifds 
= null;
InBlock.gifxBk.Close(
falsenull,null);
InBlock.gif
InBlock.gifexcel.Quit();
InBlock.gifSystem.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
InBlock.gifSystem.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
InBlock.gifSystem.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
InBlock.gifxBk 
= null;
InBlock.gifexcel 
= null;
InBlock.gifxSt 
= null;
InBlock.gifGC.Collect();
InBlock.gif
string path = Server.MapPath(this.xlfile.Text+".xls");
InBlock.gif
InBlock.gifSystem.IO.FileInfo file 
= new System.IO.FileInfo(path);
InBlock.gifResponse.Clear();
InBlock.gifResponse.Charset
="GB2312";
InBlock.gifResponse.ContentEncoding
=System.Text.Encoding.UTF8;
InBlock.gif
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
InBlock.gif
Response.AddHeader("Content-Disposition""attachment; filename=" + Server.UrlEncode(file.Name));
InBlock.gif
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
InBlock.gif
Response.AddHeader("Content-Length", file.Length.ToString());
InBlock.gif
InBlock.gif
// 指定返回的是一个不能被客户端读取的流,必须被下载
InBlock.gif
Response.ContentType = "application/ms-excel";
InBlock.gif
InBlock.gif
// 把文件流发送到客户端
InBlock.gif
Response.WriteFile(file.FullName);
InBlock.gif
// 停止页面的执行
InBlock.gif

InBlock.gifResponse.End();
ExpandedBlockEnd.gif}
 


4、
None.gifpublic void Out2Excel(string sTableName,string url)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gifExcel.Application oExcel
=new Excel.Application();
InBlock.gifWorkbooks oBooks;
InBlock.gifWorkbook oBook;
InBlock.gifSheets oSheets;
InBlock.gifWorksheet oSheet;
InBlock.gifRange oCells;
InBlock.gif
string sFile="",sTemplate="";
InBlock.gif
//
InBlock.gif
System.Data.DataTable dt=TableOut(sTableName).Tables[0];
InBlock.gif
InBlock.gifsFile
=url+"\\myExcel.xls";
InBlock.gifsTemplate
=url+"\\MyTemplate.xls";
InBlock.gif
//
InBlock.gif
oExcel.Visible=false;
InBlock.gifoExcel.DisplayAlerts
=false;
InBlock.gif
//定义一个新的工作簿
InBlock.gif
oBooks=oExcel.Workbooks;
InBlock.gifoBooks.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);
InBlock.gifoBook
=oBooks.get_Item(1);
InBlock.gifoSheets
=oBook.Worksheets;
InBlock.gifoSheet
=(Worksheet)oSheets.get_Item(1);
InBlock.gif
//命名该sheet
InBlock.gif
oSheet.Name="Sheet1";
InBlock.gif
InBlock.gifoCells
=oSheet.Cells;
InBlock.gif
//调用dumpdata过程,将数据导入到Excel中去
InBlock.gif
DumpData(dt,oCells);
InBlock.gif
//保存
InBlock.gif
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
InBlock.gifoBook.Close(
false, Type.Missing,Type.Missing);
InBlock.gif
//退出Excel,并且释放调用的COM资源
InBlock.gif
oExcel.Quit();
InBlock.gif
InBlock.gifGC.Collect();
InBlock.gifKillProcess(
"Excel");
ExpandedBlockEnd.gif}

None.gif
None.gif
private void KillProcess(string processName)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gifSystem.Diagnostics.Process myproc
= new System.Diagnostics.Process();
InBlock.gif
//得到所有打开的进程
InBlock.gif
try
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
foreach (Process thisproc in Process.GetProcessesByName(processName))
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
if(!thisproc.CloseMainWindow())
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifthisproc.Kill();
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

InBlock.gif
catch(Exception Exc)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
throw new Exception("",Exc);
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/yknb/archive/2006/06/23/434084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值