在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
此法将html中所有的内容,如按钮,表格,图片等全部输出到Execl中。
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文档等。下面的方法,也均用了这个属性。 System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1是你在窗体中拖放的控件 HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;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","attachment;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 void CreateExcel(DataSet ds,string FileName)
4、将dataview导出execl 若想实现更加富于变化或者行列不规则的execl导出时,可用本法。 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]).HorizontalAlignment = 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[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐 } else if(col.DataType == System.Type.GetType("System.String")) { excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString(); xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,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]).HorizontalAlignment = XlHAlign.xlHAlignCenter; // //设置选中的部分的颜色 // xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select(); xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).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]).Columns.AutoFit(); // //设置整个报表的标题为跨列居中 // xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select(); xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection; // //绘制边框 // xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1; xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗 xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.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(".")+"file://%22+this.xlfile.text+%22.xls%22,sheetexportactionenum.ssexportactionnone,microsoft.office.interop.owc.sheetexportformat.ssexporthtml/); xBk.SaveCopyAs(Server.MapPath(".")+"file://%22+this.xlfile.text+%22.xls/"); ds = null; xBk.Close(false, null,null); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 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(file.Name)); // 添加头信息,指定文件大小,让浏览器能够显示下载进度 Response.AddHeader("Content-Length", file.Length.ToString()); // 指定返回的是一个不能被客户端读取的流,必须被下载 Response.ContentType = "application/ms-excel"; // 把文件流发送到客户端 Response.WriteFile(file.FullName); // 停止页面的执行 Response.End(); }
5、将execl文件导出到服务器上,再下载。 public void Out2Excel(string sTableName,string url) 2、方法2:{ Excel.Application oExcel=new Excel.Application(); Workbooks oBooks; Workbook oBook; Sheets oSheets; Worksheet oSheet; Range oCells; string sFile="",sTemplate=""; // System.Data.DataTable dt=TableOut(sTableName).Tables[0]; sFile=url+"\\myExcel.xls"; sTemplate=url+"\\MyTemplate.xls"; // oExcel.Visible=false; oExcel.DisplayAlerts=false; //定义一个新的工作簿 oBooks=oExcel.Workbooks; oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing); oBook=oBooks.get_Item(1); oSheets=oBook.Worksheets; oSheet=(Worksheet)oSheets.get_Item(1); //命名该sheet oSheet.Name="Sheet1"; oCells=oSheet.Cells; //调用dumpdata过程,将数据导入到Excel中去 DumpData(dt,oCells); //保存 oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); oBook.Close(false, Type.Missing,Type.Missing); //退出Excel,并且释放调用的COM资源 oExcel.Quit(); GC.Collect(); KillProcess("Excel"); } private void KillProcess(string processName) { System.Diagnostics.Process myproc= new System.Diagnostics.Process(); //得到所有打开的进程 try { foreach (Process thisproc in Process.GetProcessesByName(processName)) { if(!thisproc.CloseMainWindow()) { thisproc.Kill(); } } } catch(Exception Exc) { throw new Exception("",Exc); } }
protected void ExportExcel() if(ds1==null) return;
string saveFileName="";
string oldCaption=Title_label .Text.Trim ();
worksheet.Cells[1,1]=Title_label .Text.Trim ();
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
if(ds1.Tables[0].Columns.Count<1) 三、附注: 虽然都是实现导出execl的功能,但在asp.net和winform的程序中,实现的代码是各不相同的。在asp.net中,是在服务器端读取数据,在服务器端把数据以ms-execl的格式,以Response输出到浏览器(客户端);而在winform中,是把数据读到客户端(因为winform运行端就是客户端),然后调用客户端安装的office组件,将读到的数据写在execl的工作簿中。
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn); DataSet ds=new DataSet(); da.Fill(ds,"table1"); DataTable dt=ds.Tables["table1"]; string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数 FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write); StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312")); sw.WriteLine("自动编号,姓名,年龄"); foreach(DataRow dr in dt.Rows) { sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]); } sw.Close(); Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载 Response.WriteFile(name); // 把文件流发送到客户端 Response.End(); |
请发表评论