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

本文汇总了ASP.NET里导出Excel表的方法,包括由DataSet生成、使用微软C++写的ACTIVEX控件、由DataGrid生成以及由DataView生成等方法,并给出了详细的代码实现,还涉及数据处理、格式设置等内容。

None.gif//1、由dataset生成
None.gif

None.gif
public void CreateExcel(DataSet ds,string typeid,string FileName) 
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif{
InBlock.gif   HttpResponse resp;
InBlock.gif   resp 
= Page.Response;
InBlock.gif   resp.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
InBlock.gif   resp.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.gif   DataRow[] 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.gif    colHeaders 
+=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.gif     ls_item 
+= row[i].ToString() +"\n";
InBlock.gif     
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据    
InBlock.gif
     resp.Write(ls_item);
InBlock.gif     ls_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
None.gif 
None.gif
None.gif
//2、使用微软的C++写的ACTIVEX控件:http://download.microsoft.com/download/OfficeXPDev/sample/1.0/WIN98MeXP/EN-US/Dsoframerctl.exe
None.gif
//3、由datagrid生成:
None.gif

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

None.gif
None.gif用法:ToExcel(datagrid1);
None.gif
None.gif
None.gif
//4、这个用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.gif   Application 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.gif   excel
= new ApplicationClass();
InBlock.gif  
InBlock.gif   xBk 
= excel.Workbooks.Add(true);
InBlock.gif   
InBlock.gif   xSt 
= (_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.gif    colIndex
++;
InBlock.gif    excel.Cells[
4,colIndex] = col.ColumnName;
InBlock.gif    xSt.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.gif    rowIndex 
++;
InBlock.gif    colIndex 
= 1;
InBlock.gif    
foreach(DataColumn col in dv.Table.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     colIndex 
++;
InBlock.gif     
if(col.DataType == System.Type.GetType("System.DateTime"))
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif      excel.Cells[rowIndex,colIndex] 
= (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
InBlock.gif      xSt.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.gif      excel.Cells[rowIndex,colIndex] 
= "'"+row[col.ColumnName].ToString();
InBlock.gif      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment 
= XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
ExpandedSubBlockEnd.gif
     }

InBlock.gif     
else
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif      excel.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.gif   excel.Cells[rowSum,
2= "合计";
InBlock.gif   xSt.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.gif   xSt.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.gif   xSt.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.gif   xSt.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.gif   xSt.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.gif   xSt.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.gif   ds 
= null;
InBlock.gif            xBk.Close(
falsenull,null);
InBlock.gif   
InBlock.gif            excel.Quit();
InBlock.gif            System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
InBlock.gif            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
InBlock.gif    System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
InBlock.gif            xBk 
= null;
InBlock.gif            excel 
= null;
InBlock.gif   xSt 
= null;
InBlock.gif            GC.Collect();
InBlock.gif   
string path = Server.MapPath(this.xlfile.Text+".xls");
InBlock.gif
InBlock.gif   System.IO.FileInfo file 
= new System.IO.FileInfo(path);
InBlock.gif   Response.Clear();
InBlock.gif   Response.Charset
="GB2312";
InBlock.gif   Response.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.gif   Response.End();
ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/acelove/archive/2005/02/21/106886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值