C#将数据导出到l汇总.docx_第1页
C#将数据导出到l汇总.docx_第2页
C#将数据导出到l汇总.docx_第3页
C#将数据导出到l汇总.docx_第4页
C#将数据导出到l汇总.docx_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

转C# 将数据导出到Execl汇总 Posted on 2010-06-18 10:25 O零O 阅读(10) 评论(0) 编辑 收藏 所属分类: .NET资料库 转C# 将数据导出到Execl汇总本文转自:/wjg121/archive/2008/12/20/1359117.html一、中导出Execl的方法:在中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件输出流写给浏览器。在Response输出时,t分隔的数据,导出execl时,等价于分列,n等价于换行。 1、将整个html全部输出execl此法将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文档等。下面的方法,也均用了这个属性。2、将DataGrid控件中的数据导出Execl上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,DataGrid控件上的数据。 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); 3、将DataSet中的数据导出Execl有了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。那么把DataSet中的数据导出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。说明:参数ds应为填充有数据表的DataSet,文件名是全名,包括后缀名,如execl2006.xls CodepublicvoidCreateExcel(DataSetds,stringFileName)HttpResponseresp;resp=Page.Response;resp.ContentEncoding=System.Text.Encoding.GetEncoding(GB2312);resp.AppendHeader(Content-Disposition,attachment;filename=+FileName);stringcolHeaders=,ls_item=;/定义表对象与行对象,同时用DataSet对其值进行初始化DataTabledt=ds.Tables0;DataRowmyRow=dt.Select();/可以类似dt.Select(id10)之形式达到数据筛选目的inti=0;intcl=dt.Columns.Count;/取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符for(i=0;icl;i+)if(i=(cl-1)/最后一列,加ncolHeaders+=dt.Columnsi.Caption.ToString()+n;elsecolHeaders+=dt.Columnsi.Caption.ToString()+t;resp.Write(colHeaders);/向HTTP输出流中写入取得的数据信息/逐行处理数据foreach(DataRowrowinmyRow)/当前行数据写入HTTP输出流,并且置空ls_item以便下行数据for(i=0;icl;i+)if(i=(cl-1)/最后一列,加nls_item+=rowi.ToString()+n;elsels_item+=rowi.ToString()+t;resp.Write(ls_item);ls_item=;resp.End(); 4、将dataview导出execl 若想实现更加富于变化或者行列不规则的execl导出时,可用本法。 上面的方面,均将要导出的execl数据,直接给浏览器输出文件流,下面的方法是首先将其存到服务器的某个文件夹中,然后把文件发送到客户端。这样可以持久的把导出的文件存起来,以便实现其它功能。 5、将execl文件导出到服务器上,再下载。二、winForm中导出Execl的方法:1、方法1:CodepublicvoidOutputExcel(DataViewdv,stringstr)/dv为要输出到Excel的数据,str为标题名称GC.Collect();Applicationexcel;/=newApplication();introwIndex=4;intcolIndex=1;_WorkbookxBk;_WorksheetxSt;excel=newApplicationClass();xBk=excel.Workbooks.Add(true);xSt=(_Worksheet)xBk.ActiveSheet;/取得标题/foreach(DataColumncolindv.Table.Columns)colIndex+;excel.Cells4,colIndex=col.ColumnName;xSt.get_Range(excel.Cells4,colIndex,excel.Cells4,colIndex).HorizontalAlignment=XlVAlign.xlVAlignCenter;/设置标题格式为居中对齐/取得表格中的数据/foreach(DataRowViewrowindv)rowIndex+;colIndex=1;foreach(DataColumncolindv.Table.Columns)colIndex+;if(col.DataType=System.Type.GetType(System.DateTime)excel.CellsrowIndex,colIndex=(Convert.ToDateTime(rowcol.ColumnName.ToString().ToString(yyyy-MM-dd);xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment=XlVAlign.xlVAlignCenter;/设置日期型的字段格式为居中对齐elseif(col.DataType=System.Type.GetType(System.String)excel.CellsrowIndex,colIndex=+rowcol.ColumnName.ToString();xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment=XlVAlign.xlVAlignCenter;/设置字符型的字段格式为居中对齐elseexcel.CellsrowIndex,colIndex=rowcol.ColumnName.ToString();/加载一个合计行/introwSum=rowIndex+1;intcolSum=2;excel.CellsrowSum,2=合计;xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,2).HorizontalAlignment=XlHAlign.xlHAlignCenter;/设置选中的部分的颜色/xSt.get_Range(excel.CellsrowSum,colSum,excel.CellsrowSum,colIndex).Select();xSt.get_Range(excel.CellsrowSum,colSum,excel.CellsrowSum,colIndex).Interior.ColorIndex=19;/设置为浅黄色,共计有56种/取得整个报表的标题/excel.Cells2,2=str;/设置整个报表的标题格式/xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Bold=true;xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Size=22;/设置报表表格为最适应宽度/xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,colIndex).Select();xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,colIndex).Columns.AutoFit();/设置整个报表的标题为跨列居中/xSt.get_Range(excel.Cells2,2,excel.Cells2,colIndex).Select();xSt.get_Range(excel.Cells2,2,excel.Cells2,colIndex).HorizontalAlignment=XlHAlign.xlHAlignCenterAcrossSelection;/绘制边框/xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,colIndex).Borders.LineStyle=1;xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,2).BordersXlBordersIndex.xlEdgeLeft.Weight=XlBorderWeight.xlThick;/设置左边线加粗xSt.get_Range(excel.Cells4,2,excel.Cells4,colIndex).BordersXlBordersIndex.xlEdgeTop.Weight=XlBorderWeight.xlThick;/设置上边线加粗xSt.get_Range(excel.Cells4,colIndex,excel.CellsrowSum,colIndex).BordersXlBordersIndex.xlEdgeRight.Weight=XlBorderWeight.xlThick;/设置右边线加粗xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,colIndex).BordersXlBordersIndex.xlEdgeBottom.Weight=XlBorderWeight.xlThick;/设置下边线加粗/显示效果/excel.Visible=true;/xSt.Export(Server.MapPath(.)+this.xlfile.Text+.xls,SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);xBk.SaveCopyAs(Server.MapPath(.)+this.xlfile.Text+.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();stringpath=Server.MapPath(this.xlfile.Text+.xls);System.IO.FileInfofile=newSystem.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(); 方法2: CodeSqlConnectionconn=newSqlConnection(System.Configuration.ConfigurationSettings.AppSettingsconn);SqlDataAdapterda=newSqlDataAdapter(select*fromtb1,conn);DataSetds=newDataSet();da.Fill(ds,table1);DataTabledt=ds.Tablestable1;stringname=System.Configuration.ConfigurationSettings.AppSettingsdownloadurl.ToString()+DateTime.Today.ToString(yyyyMMdd)+newRandom(DateTime.Now.Millisecond).Next(10000).ToString()+.csv;/存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数FileStreamfs=newFileStream(name,FileMode.Create,FileAccess.Write);StreamWritersw=newStreamWriter(fs,System.Text.Encoding.GetEncoding(gb2312);sw.WriteLine(自动编号,姓名,年龄);foreach(DataRowdrindt.Rows)sw.WriteLine(drID+,+drvName+,+driAge);sw.Close();Response.AddHeader(Content-Disposition,attachment;filename=+Server.UrlEncode(name);Response.ContentType=application/ms-excel;/指定返回的是一个不能被客户端读取的流,必须被下载Response.WriteFile(name);/把文件流发送到客户端Response.End(); publicvoidOut2Excel(stringsTableName,stringurl)Excel.ApplicationoExcel=newExcel.Application();WorkbooksoBooks;WorkbookoBook;SheetsoSheets;WorksheetoSheet;RangeoCells;stringsFile=,sTemplate=;/System.Data.DataTabledt=TableOut(sTableName).Tables0;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);/命名该sheetoSheet.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);privatevoidKillProcess(stringprocessName)System.Diagnostics.Processmyproc=newSystem.Diagnostics.Process();/得到所有打开的进程tryforeach(ProcessthisprocinProcess.GetProcessesByName(processName)if(!thisproc.CloseMainWindow()thisproc.Kill();catch(ExceptionExc)thrownewException(,Exc);2CodeprotectedvoidExportExcel()gridbind();if(ds1=null)return;stringsaveFileName=;/boolfileSaved=false;SaveFileDialogsaveDialog=newSaveFileDialog();saveDialog.DefaultExt=xls;saveDialog.Filter=Excel文件|*.xls;saveDialog.FileName=Sheet1;saveDialog.ShowDialog();saveFileName=saveDialog.FileName;if(saveFileName.IndexOf(:)0)return;/被点了取消/excelapp.Workbooks.Open(App.path&工程进度表.xls)Excel.ApplicationxlApp=newExcel.Application();objectmissing=System.Reflection.Missing.Value; if(xlApp=null)MessageBox.Show(无法创建Excel对象,可能您的机子未安装Excel);return;Excel.Workbooksworkbooks=xlApp.Workbooks;Excel.Workbookworkbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheetworksheet=(Excel.Worksheet)workbook.Worksheets1;/取得sheet1Excel.Rangerange;stringoldCaption=Title_label.Text

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论