DataGrid的数据源是一个dataview,将这个dataview循环写入到Excel1.首先,产生一个文件夹来存放Excel文件private string genReportPath() { try { string _path="..//ReportDoc//DRI"; if (!Directory.Exists(Server.MapPath(_path))) { Directory.CreateDirectory(Server.MapPath(_path)); } return _path; } catch(Exception er) { throw er; } }2.确定Excel文件string reportpath=this.genReportPath()+"//"+_reportname+".xls"; 3.生成Excel文件this.genExcel(ds_DRI,Server.MapPath(reportpath).ToString());4.生成函数(需要一个DataSet,还需要一个路径)private void genExcel(DataSet ds,string ReportPath) { try { //删除重复的文件; if (File.Exists(ReportPath)) { File.Delete(ReportPath); } FileStream fsobj=new FileStream(ReportPath,System.IO.FileMode.Create,FileAccess.ReadWrite); //生成一个文件流 StreamWrite _sw=new StreamWriter(fsobj,System.Text.UnicodeEncoding.Unicode);//生成一个写入器//开始写入DataTable dt=ds.Tables[0]; for(int j=0;j<countMRD;j++) { _sw.Write(dt.Rows[j][0].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][1].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][2].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][3].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][4].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][5].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][6].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][7].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][8].ToString().Trim()+"\t"); _sw.Write(dt.Rows[j][9].ToString().Trim()+"\t");}_sw.close();fsobj.close(); } catch(Exception er) { throw er; }
datagrid1.DataSource=ds.Tables[0]; datagrid1.DataBind();