C#导出Excel方法大全.pdf
C C#导导出出 E Ex xc ce el l 方方法法大大全全-CAL-FENGHAI.-(YICAI)-Company One1C#C#导出导出 EXCELEXCEL 方法大全方法大全C#中常需要把报表数据导出 Excel,下面详细介绍 6 种方法:第一种方法比较罗嗦,主要介绍如何调用,含注释给不熟导出 EXCEL 者知其原理第二方法直接套用,代码简单明了。个人推荐这种,直接套用,非常方便。第三到第六种就不一一介绍了。方法方法 1 1页面增加一个按钮,单击事件添加如下方法:protected void Button1_Click(object sender,EventArgs e)Export(application/ms-excel,学生信息列表.xls);private void Export(string FileType,string FileName)=GB2312;=(Content-Disposition,attachment;filename=+(FileName,.ToString();=FileType;=false;StringWriter tw=new StringWriter();HtmlTextWriter hw=new HtmlTextWriter(tw);(hw);();();1”ls);private void Export(string FileType,string FileName)=GB2312;=(Content-Disposition,attachment;filename=+(FileName,.ToString();=FileType;=false;StringWriter tw=new StringWriter();HtmlTextWriter hw=new HtmlTextWriter(tw);(hw);();();public override void VerifyRenderingInServerForm(Control control)2 前台:读取 Excel 数据的代码private DataSet CreateDataSource()string strCon;strCon=Provider=Source=+()+;Extended Properties=Excel;OleDbConnection olecon=new OleDbConnection(strCon);OleDbDataAdapter myda=new OleDbDataAdapter(SELECT*FROM Sheet1$,strCon);DataSet myds=new DataSet();(myds);return myds;protected void Button1_Click(object sender,EventArgs e)3 =CreateDataSource();();方法方法 2 2,直接调用,直接调用页面增加一个按钮btnExcel,单击btnExcel事件添加如下方法:主要替换GridViewGridView 名称名称和写你的 GridViewGridView 数据绑定方法数据绑定方法 BindGrid()BindGrid()就行了。protected void btnExcel_Click(object sender,EventArgs e)ToExcel;ls);=utf-8;=utf-8);=application/ms-excel;alue=i+1;for(int j=1;j;j+)parmj.Value=ij;();rowRead+;percent=(float)(100*rowRead)/totalCount;.;if(i=请稍后.;.();();.;.();range=2,1,=true;(FileName);dt=new filePath=d:;object oMissing=xlApp=new();try=false;=false;oBooks=;xlWorkbook=null;xlWorkbook=(filePath,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing);xlWorksheet;4oString();if(k -1)stringBuffer+=t;stringBuffer+=n;elect();/粘贴!(oMissing,oMissing);/清空系统剪切板。);/保存并关闭这个工作簿。(oMissing,oMissing);=null;5