一、中导出Excel的方法:在 中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件输出流写给浏览器。
在Response输出时,t分隔的数据,导出Excel时,等价于分列,n等价于换行。
1、将整个 html全部输出Excel此法将html中所有的内容,如按钮,表格,图片等全部输出到Excel中。
Response.Clear();Response.Buffer= true;Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");Response.ContentEncoding=System.Text.Encoding.UTF8;Response.ContentType = "application/vnd.ms-excel";this.EnableViewState = false;这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。
ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。
同理,我们也可以输出(导出)图片、word文档等。
下面的方法,也均用了这个属性。
2、将DataGrid控件中的数据导出Excel上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。
而我们一般要导出的是数据,DataGrid控件上的数据。
System.Web.UI.Control ctl=this.DataGrid1;//DataGrid1是你在窗体中拖放的控件HttpContext.Current.Response.AppendHeader("Content-Disposition","atta chment;filename=Excel.xls");HttpContext.Current.Response.Charset ="UTF-8";HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;HttpContext.Current.Response.ContentType ="application/ms-excel";ctl.Page.EnableViewState =false;System.IO.StringWriter tw = new System.IO.StringWriter() ;System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw); ctl.RenderControl(hw);HttpContext.Current.Response.Write(tw.ToString());HttpContext.Current.Response.End();如果你的DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。
而不是你select语句的全部信息。
为方便使用,写成方法如下:public void DGToExcel(System.Web.UI.Control ctl){HttpContext.Current.Response.AppendHeader("Content-Disposition","a ttachment;filename=Excel.xls");HttpContext.Current.Response.Charset ="UTF-8";HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;HttpContext.Current.Response.ContentType ="application/ms-excel"; ctl.Page.EnableViewState =false;System.IO.StringWriter tw = new System.IO.StringWriter() ;System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);ctl.RenderControl(hw);HttpContext.Current.Response.Write(tw.ToString());HttpContext.Current.Response.End();}用法:DGToExcel(datagrid1);页面中需要添加下面这个空方法.public override void VerifyRenderingInServerForm(Control control) {}3、将DataSet中的数据导出Excel有了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。
那么把DataSet中的数据导出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。
说明:参数ds应为填充有数据表的DataSet,文件名是全名,包括后缀名,如Excel2006.xlspublic void CreateExcel(DataSet ds,string FileName){HttpResponse resp;resp = Page.Response;resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");resp.AppendHeader("Content-Disposition","attachment;filename="+FileName);string colHeaders= "", ls_item="";//定义表对象与行对象,同时用DataSet对其值进行初始化DataTable dt=ds.Tables[0];DataRow[] myRow=dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的int i=0;int cl=dt.Columns.Count;//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符 for(i=0;i<cl;i++){if(i==(cl-1))//最后一列,加n{colHeaders +=dt.Columns[i].Caption.ToString() +"n";}else{colHeaders+=dt.Columns[i].Caption.ToString()+"t";}}resp.Write(colHeaders);//向HTTP输出流中写入取得的数据信息//逐行处理数据foreach(DataRow row in myRow){//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据for(i=0;i<cl;i++){if(i== (cl-1))//最后一列,加n{ls_item +=row[i].ToString()+"n";}else{ls_item+=row[i].ToString()+"t";}}resp.Write(ls_item);ls_item="";}resp.End();}4、将dataview导出excel若想实现更加富于变化或者行列不规则的excel导出时,可用本法。
public void OutputExcel(DataView dv,string str){//dv为要输出到Excel的数据,str为标题名称GC.Collect();Application excel;// = new Application();int rowIndex=4;int colIndex=1;_Workbook xBk;_Worksheet xSt;excel= new ApplicationClass();xBk = excel.Workbooks.Add(true);xSt = (_Worksheet)xBk.ActiveSheet;////取得标题//foreach(DataColumn col in dv.Table.Columns){colIndex++;excel.Cells[4,colIndex] = col.ColumnName;xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).Ho rizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐 }////取得表格中的数据//foreach(DataRowView row in dv){rowIndex ++;colIndex = 1;foreach(DataColumn col in dv.Table.Columns){colIndex ++;if(col.DataType == System.Type.GetType("System.DateTime")){excel.Cells[rowIndex,colIndex] =(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowInd ex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐}elseif(col.DataType == System.Type.GetType("System.String")){excel.Cells[rowIndex,colIndex] ="'"+row[col.ColumnName].ToString();xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowInd ex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐}else{excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString(); }}}////加载一个合计行//int rowSum = rowIndex + 1;int colSum = 2;excel.Cells[rowSum,2] = "合计";xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).Horizon talAlignment = XlHAlign.xlHAlignCenter;////设置选中的部分的颜色//xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colInd ex]).Select();xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colInd ex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种////取得整个报表的标题//excel.Cells[2,2] = str;////设置整个报表的标题格式//xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true; xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22; ////设置报表表格为最适应宽度//xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Colum ns.AutoFit();////设置整个报表的标题为跨列居中//xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select(); xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Horizontal Alignment = XlHAlign.xlHAlignCenterAcrossSelection;////绘制边框//xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borde rs.LineStyle = 1;xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBo rdersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[Xl BordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex] ).Borders[XlBordersIndex.xlEdgeRight].Weight =XlBorderWeight.xlThick;//设置右边线加粗xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]). Borders[XlBordersIndex.xlEdgeBottom].Weight =XlBorderWeight.xlThick;//设置下边线加粗////显示效果//excel.Visible=true;//xSt.Export(Server.MapPath(".")+""+this.xlfile.Text+".xls",SheetE xportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.Sheet ExportFormat.ssExportHTML);xBk.SaveCopyAs(Server.MapPath(".")+""+this.xlfile.Text+".xls");ds = null;xBk.Close(false, null,null);excel.Quit();System.Runtime.InteropServices.Marshal.ReleaseComObject(x Bk);System.Runtime.InteropServices.Marshal.ReleaseComObject(e xcel);System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);xBk = null;excel = null;xSt = null;GC.Collect();string path = Server.MapPath(this.xlfile.Text+".xls");System.IO.FileInfo file = new System.IO.FileInfo(path);Response.Clear();Response.Charset="GB2312";Response.ContentEncoding=System.Text.Encoding.UTF8;// 添加头信息,为"文件下载/另存为"对话框指定默认文件名Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode());// 添加头信息,指定文件大小,让浏览器能够显示下载进度Response.AddHeader("Content-Length", file.Length.ToString());// 指定返回的是一个不能被客户端读取的流,必须被下载Response.ContentType = "application/ms-excel";// 把文件流发送到客户端Response.WriteFile(file.FullName);// 停止页面的执行Response.End();}上面的方面,均将要导出的excel数据,直接给浏览器输出文件流,下面的方法是首先将其存到服务器的某个文件夹中,然后把文件发送到客户端。