asp.net导出excel数据的常见方法汇总
本文实例讲述了asp.net中一些常用的excel数据导出方法,同时也介绍了在数据导入或导出时可能碰到的一些问题总结,分享给大家供大家参考。希望文章对你会有所帮助。具体实现方法如下:
1、由dataset生成
publicvoidCreateExcel(DataSetds,stringtypeid,stringFileName) { HttpResponseresp; resp=Page.Response; resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312"); resp.AppendHeader("Content-Disposition","attachment;filename="+FileName); stringcolHeaders="",ls_item=""; inti=0; //定义表对象与行对像,同时用DataSet对其值进行初始化 DataTabledt=ds.Tables[0]; DataRow[]myRow=dt.Select(""); //typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 if(typeid=="1") { //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符 for(i=0;i colHeaders+=dt.Columns[i].Caption.ToString()+"t"; colHeaders+=dt.Columns[i].Caption.ToString()+"n"; //向HTTP输出流中写入取得的数据信息 resp.Write(colHeaders); //逐行处理数据 foreach(DataRowrowinmyRow) { //在当前行中,逐列获得数据,数据之间以t分割,结束时加回车符n for(i=0;i ls_item+=row[i].ToString()+"t"; ls_item+=row[i].ToString()+"n"; //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 resp.Write(ls_item); ls_item=""; } } else { if(typeid=="2") { //从DataSet中直接导出XML数据并且写到HTTP输出流中 resp.Write(ds.GetXml()); } } //写缓冲区中的数据到HTTP头文件中 resp.End(); }
2、由datagrid生成
publicvoidToExcel(System.Web.UI.Controlctl) { 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";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword ctl.Page.EnableViewState=false; System.IO.StringWriter tw=newSystem.IO.StringWriter(); System.Web.UI.HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw); ctl.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); }
用法:ToExcel(datagrid1);
3、这个用dataview
publicvoidOutputExcel(DataViewdv,stringstr) { // //TODO:在此处添加构造函数逻辑 // //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.Cells[4,colIndex]=col.ColumnName; xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment=XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐 } // //取得表格中的数据 // foreach(DataRowViewrowindv) { rowIndex++; colIndex=1; foreach(DataColumncolindv.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(); } } } // //加载一个合计行 // introwSum=rowIndex+1; intcolSum=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(".")+"\"+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(); }
导入、导出EXCEL中的一些问题汇总
一、在项目中的添加引用:
右击项目资源管理器的引用-->添加引用-->选择.NET选项卡-->选择Microsoft.Office.Interop.Excel-->确定;
在选择时注意一下.NET组件的版本号,本例的12.0.0.0是Office2007的版本:
二、在项目中使用Microsoft.Office.Interop.Excel:
如果想使用Microsoft.Office.Interop.Excel,首先需要在项目中引用命名空间:
usingMicrosoft.Office.Interop.Excel;
三、建立Excel.Application相关对象
//建立Application对象 Microsoft.Office.Interop.Excel.ApplicationmyExcel=newApplication(); //建立Workbooks对象 WorkbooksmyBooks=myExcel.Application.Workbooks; //建立一个System.Reflection.Missing的object对象 objectoMissing=System.Reflection.Missing.Value;
四、打开或新建Excel的book文件
//打开Excel文件,注意里的“ExccelFilePath”为Excel文件在服务器上的物理地址,包括文件名 WorkbookmyBook=myBooks.Open(ExccelFilePath,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing); //新建Workseet对象,,此处为要操作的工作表,当前要操作的工作表的获取方法有两种:使用工作表的索引值或使用工作表的名称,名称默认为:“sheet1”/“Sheet2”等 WorksheetmySheet=(Worksheet)myBook.Worksheets[1]; //如果是新建EXCEL工作簿,需要设置如下两行内容,以保证工作簿中有一个工作表, Workbookworkbook1=excel1.Workbooks.Add(true); WorksheetmySheet=(Worksheet)workbook1.Worksheets["sheet1"]; //设置EXCEL对象是否显示界面,默认为false不显示界面 myExcel.Visble=true;
五、一些比较重要的针对Excel的操作
1、获取Range对象
①、获取一个单元格的Range对象:
//选择第一行、第一列的单元的单元格为Range对象 Ranger=(Excel.Range)mySheet.Cells[1,1]; //选择多个连续的单元格为Range对象 Ranger=(Excel.Range)Range.get_Range("A1:F3")
②、给单元格赋值或取出单元格的值:
//已选择了Range对象的赋值: r.Text="中国"; //未选择Range对象的赋值: mySheet.Cells[1,2].Text="中国"; //已选择了Range对象的取值: StringstrValue=r.Text; //未选择Range对象的取值: String strValue= mySheet.Cells[1,2].Text;
③、给单元格设置边框
mySheet.Cells[2,1].BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThin,XlColorIndex.xlColorIndexAutomatic,null);//画线
④、合并单元格
//合并单元格前先要将要合并的单元格选择为Range对象 Ranger=Range.get_Range("A1:F3"); //然后现设置合并单元格 r.MergeCells=true;
⑤、设置单元格的字体、字号、背景色等属性
mySheet.Cells[1,1].Font.Name="黑体"; mySheet.Cells[1,1].Font.Size=20; mySheet.Rows["1:1"].RowHeight=40; mySheet.Cells[1,1].Interior.Color=Color.FromArgb(224,224,224);//设置颜色
⑥、删除一行:
//首先获取要删除的行的Range Microsoft.Office.Interop.Excel.Rangerange=(Microsoft.Office.Interop.Excel.Range)mySheet.Rows[sendedRow[1],Type.Missing]; //注意删除行后删除后的行号被下面的行替换,如果逐行删除,请先从最大的行号往最小的行号删除 range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);
⑦、获取有数据的行数
introwsint=mySheet.UsedRange.Cells.Rows.Count;
六、EXCEL文件的保存与退出
1、EXCEL的保存与退出
myBook.Save(); myBooks.Close(); myExcel.Quit();
2、EXCEL指定文件保存
myBook.Close(true,FilePath+_file_Name,null);
七、释放EXCLE对象的资源与结束EXCEL 进程
关于这方面内容有好多网友都在讲多种方法,经过本人实践,以下方面才能真正做到结束EXCEL的任务进程:
1、将所有以上对EXCEL的操作放到一个方法中,
2、在操作EXCEL后,即时将不使用对象一一释放并赋null值:
System.Runtime.InteropServices.Marshal.ReleaseComObject(mysheet); mysheet=null; System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); myBook=null; System.Runtime.InteropServices.Marshal.ReleaseComObject(myBooks); myBooks=null; System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel); myExcel=null;
3、再新建一个方法,并以该方法中执行上面新建的操作EXCEL方法,并在执行完操作EXCEL方法的后面添加GC.Collect():
//下面方法中OutPutEXCEL()方法是输出EXCEL文件的对EXCEL操作的方法 privatevoidkillExcel() { outPutEXCEL(); GC.Collect(); GC.WaitForPendingFinalizers(); }
好多网友都在介绍使用GC.Collect()释放EXCEL占用的资源来结束EXCEL进行,如果将“GC.Collect();”与操作EXCEL的业务写在一个程序块中,“GC”是永远不能结束EXCEL进程的,在WEB应用程序中,这种现象是很可怕的事情。原因是GC不会清理本程序块中的垃圾内存的。
4、在业务事件中调用killEXCEL()方法:
protectedvoidLinkButton3_Click(objectsender,EventArgse) { //导出EXCEL killExcel(); }
八、一些权限的基本设置:
使用以上方法在开发环境中调试程序没有一点问题,等发布到服务器上后,程序还是不能正常运行,需要进行如下的权限设置:
.NET导出Excel遇到的80070005错误的解决方法:
检索COM类工厂中CLSID为{00024500-0000-0000-C000-000000000046}的组件时失败,原因是出现以下错误:80070005基本上.net导出excel文件,都需要如此配置一下,不配置有的时候没错,而配置后基本应该不会出错。
具体配置方法如下:
①在服务器上安装office的Excel软件.
②在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"
③依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
④在"DCOM配置"中找到"Microsoft Excel应用程序",在它上面点击右键,然后点击"属性",弹出"MicrosoftExcel应用程序属性"对话框
⑤点击"标识"标签,选择"交互式用户"
⑥点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加一个"NETWORK SERVICE"用户(注意要选择本计算机名),并给它赋予"本地启动"和"本地激活"权限.
⑦依然是"安全"标签,在"访问权限"上点击"自定义",然后点击"编辑",在弹出的"安全性"对话框中也填加一个"NETWORK SERVICE"用户,然后赋予"本地访问"权限.
⑧如果交互式用户设置后出现错误8000401a,可取消交互式用户,指定为administratr,可暂时解决此问题。进一步的解决方式还有待探讨。
⑨采用第8点的设置后,打开Excel可能会出现“无法使用对象引用或链接”,并且不能进行单元格粘贴。原因不明,取消设置后即可消失。
希望本文所述对大家的asp.net程序设计有所帮助。