1、由dataset生成
net导出excel方法汇总引用http://www.cnblogs.com/yknb/articles/434084.html
net导出excel方法汇总
public void CreateExcel(DataSet ds,string typeid,string FileName)
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总HttpResponse resp;
net导出excel方法汇总resp
= Page.Response;
net导出excel方法汇总resp.ContentEncoding
= System.Text.Encoding.GetEncoding("GB2312");
net导出excel方法汇总resp.AppendHeader(
"Content-Disposition", "attachment;filename=" + FileName);
net导出excel方法汇总
string colHeaders= "", ls_item="";
net导出excel方法汇总
int i=0;
net导出excel方法汇总
net导出excel方法汇总
//定义表对象与行对像,同时用DataSet对其值进行初始化
net导出excel方法汇总
DataTable dt=ds.Tables[0];
net导出excel方法汇总DataRow[] myRow
=dt.Select("");
net导出excel方法汇总
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
net导出excel方法汇总
if(typeid=="1")
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
net导出excel方法汇总
for(i=0;i colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
net导出excel方法汇总colHeaders
+=dt.Columns[i].Caption.ToString() +"\n";
net导出excel方法汇总
//向HTTP输出流中写入取得的数据信息
net导出excel方法汇总
resp.Write(colHeaders);
net导出excel方法汇总
//逐行处理数据
net导出excel方法汇总
foreach(DataRow row in myRow)
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
net导出excel方法汇总
for(i=0;i ls_item +=row[i].ToString() + "\t";
net导出excel方法汇总ls_item
+= row[i].ToString() +"\n";
net导出excel方法汇总
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
net导出excel方法汇总
resp.Write(ls_item);
net导出excel方法汇总ls_item
="";
net导出excel方法汇总}

net导出excel方法汇总}

net导出excel方法汇总
else
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总
if(typeid=="2")
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总
//从DataSet中直接导出XML数据并且写到HTTP输出流中
net导出excel方法汇总
resp.Write(ds.GetXml());
net导出excel方法汇总}

net导出excel方法汇总}

net导出excel方法汇总
//写缓冲区中的数据到HTTP头文件中
net导出excel方法汇总
resp.End();
net导出excel方法汇总
net导出excel方法汇总
net导出excel方法汇总}

net导出excel方法汇总
2、由datagrid生成
net导出excel方法汇总
net导出excel方法汇总
public void ToExcel(System.Web.UI.Control ctl)
net导出excel方法汇总net导出excel方法汇总
net导出excel方法汇总{
net导出excel方法汇总HttpContext.Current.Response.AppendHeader(
"Content-Disposition","attachment;filename=Excel.xls");
net导出excel方法汇总HttpContext.Current.Response.Charset
="UTF-8";
net导出excel方法汇总HttpContext.Current.Response.ContentEncoding
=System.Text.Encoding.Default;
net导出excel方法汇总HttpContext.Current.Response.ContentType
="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
net导出excel方法汇总
ctl.Page.EnableViewState =false;
net导出excel方法汇总System.IO.StringWriter tw
= new System.IO.StringWriter() ;
net导出excel方法汇总System.Web.UI.HtmlTextWriter hw
= new System.Web.UI.HtmlTextWriter (tw);
net导出excel方法汇总ctl.RenderControl(hw);
net导出excel方法汇总HttpContext.Current.Response.Write(tw.ToString());
net导出excel方法汇总HttpContext.Current.Response.End();
net导出excel方法汇总}

net导出excel方法汇总
net导出excel方法汇总用法:ToExcel(datagrid1);
net导出excel方法汇总
net导出excel方法汇总

相关文章: