.NET页面数据导出excel表方法
NET导出Excel文件

.NET导出Excel文件最近做 Excel导出功能,顺便整理了一下可用的一些导出Excel方法一般导出方式1,客户提出要将统计的结果导出到excel文件,首先利用如下方式:增加<%@page contentType="application/vnd.ms-excel;charset=GBK" %>头部说明,然后放一个table在该页面中即可了。
2,客户看过后提出了改进意见,要求保存文件的时候自动给文件一个名称,这样可以直接保存。
改进如下:增加response.setHeader("Content-Disposition", "attachment; filename="+fileName);但是却又遇到了乱码的问题:response.setHeader("Content-Disposition","attachment; filename="+new String(fileName.getBytes("GBK"),"iso-8859-1"));将文件名称的编码由GBK转换为ISO-8859-1就正常了。
GridView导出Excel尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。
总结了一下应该注意下面几点:1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview 的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的 服务器控件呈现HtmlForm 控件;4.导出后别忘记再重新设置其allowpaging属性;当我把这些都设置好以后,点击[导出],出现了只能在执行Render() 的过程中调用RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:修改你的aspx文件中的:<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>增加红色的部分就ok了。
.net导出excel的四种方法及评测

一、概述在日常工作和生活中,我们经常会遇到需要导出Excel表格的情况,无论是数据分析报告、财务报表还是客户清单,Excel都是非常常见的工具。
而对于使用.net框架的开发人员来说,如何在程序中实现Excel 导出也是一个常见的需求。
本文将介绍四种常见的.net导出Excel的方法,并对它们进行评测,以便开发人员在实际项目中选择最合适的方案。
二、利用Microsoft.Office.Interop.Excel进行导出1. 使用COM组件操作ExcelMicrosoft.Office.Interop.Excel是.NET对Excel COM组件的封装,开发人员可以通过这个组件来操作Excel。
通过这种方法,可以实现对Excel表格的创建、读取、修改和导出。
2. 优点a. 功能丰富:可以实现对Excel表格的各种操作,包括格式设置、数据写入等。
b. 灵活性高:可以实现对Excel表格的各种定制操作,满足不同需求。
3. 缺点a. 依赖性强:需要安装Office软件,才能在服务器上执行。
b. 性能低:由于是通过COM组件进行操作,性能相对较低,特别是在大数据量的情况下。
三、利用NPOI库进行导出1. 使用NPOI库NPOI是一个.NET操作Office文件的开源库,支持对Excel、Word、PowerPoint的读写操作。
通过NPOI库,开发人员可以对Excel表格进行创建、读取、修改和导出。
2. 优点a. 轻量级:NPOI库较轻量,不需要依赖Office软件。
b. 跨评台性:NPOI库可以在Windows、Linux和MacOS等操作系统上使用。
3. 缺点a. API复杂:相对于Microsoft.Office.Interop.Excel,NPOI库的API设计相对复杂。
b. 功能相对局限:相对于Microsoft.Office.Interop.Excel,NPOI库的功能相对局限一些。
四、利用EPPlus库进行导出1. 使用EPPlus库EPPlus是一个用于操作Excel文件的开源库,可以在.NET环境下实现对Excel表格的创建、读取、修改和导出。
怎么将ASP.NET导出Excel表格

怎么将导出Excel表格怎么将导出Excel表格之前一直想研究导出Excel表格来着,但一直没有时间,这几天因为一个项目的需要,所以就钻研了一下。
小面小编告诉你怎么将导出Excel表格:1.在DownStudent.aspx页面上添加一个Label标签用来显示“请选择要查看数据的条件”静态文本;2.在该页面上添加DropDownList控件用来控制显示数据以及输出数据的条件,绑定DropDownList1_SelectedIndexChanged函数;3.在该页面上添加GridView控件来显示由DropDownList控件指定条件的数据;4.在该页面上添加SqlDataSource控件用来连接数据库并将查询的结果返给GridView控件;5.最后是一个确认按钮,绑定Button1_Click函数。
后台代码实现(DownStudent.aspx.cs):(具体代码见附录)后台代码的实现是导出Excel表格的关键所在,是重中之重。
1.首先是命名空间的问题,因为这里是导出Excel表格用到了输入输出流,所以必须在命名空间里引用IO流(using System.IO;),我这里用的是SQLServer数据库,所以还要用到(using System.Data;和using System.Data,Sql;);2.实现DropDownList1_SelectedIndexChanged函数,注意:SelectedIndexChanged方法的实现必须基于DropDownList1控件的AutoPostBack属性要设置为True(否则SelectedIndexChanged 方法无效),而DropDownList1_SelectedIndexChanged函数主要实现的就是根据DropDownList1控件选定的条件修改SqlDataSource 控件的SelectComand的值;代码示例:SqlDataSource1.SelectCommand = "SELECT [Chufen], [Zhibu], [Zhuanzheng] from bizusers WHERE (bizusers.Zhibu ='" + DropDownList1.SelectedItem.Text + "')";3.Button1_Click函数是精华所在,该函数实现思想是:先获取一个数据库连接(方法比较多,有传统通过SqlConnect获取的,也有调用外部类实现的),然后是一条SQL语句(Select查询字符串),再者是调用外部类的方法根据SQL语句生成一个DataSet结果集对象(把SQL 语句查询到的值放入DataSet里,方便下一次使用,而不是再去访问一次数据库),最后,调用CreateExcel函数,注意参数;4.实现CreateExcel函数(就是对生成的DataSet的进一步操作了);其他引用文件说明:在App_Code文件夹里主要有3个外部类,QueryString.cs文件这里不是重点,故跳过。
网页数据如何简单导出excel

网页数据如何简单导出excel在浏览网页时,遇到我们需要的网页数据时,如文字、图片等,如何能简单的导出到Excel 中,方便在本地电脑中查看和编辑呢?当然是有办法的啦!下面就为大家介绍几种简单快速的将网页数据导出到Excel的方法,大家可以灵活运用。
一、通过浏览器导出网页数据具体操作:打开某网页后,右键点击网页空白处,在下拉列表中选择“另存为”,然后在弹出的保存窗口中选择保存类型为“网页全部”。
选择保存位置后确定,保存后就会自动保存两个文件,一个是网址,另一个是保存网页内容元素。
如何导出网页数据,以赶集网采集为例图1二、通过网页数据采集器导出网页数据先通过网页数据采集器,将网页数据采集下来,然后再导出为需要的格式即可。
本文使用的是操作简单、功能强大的八爪鱼采集器。
以下是一个八爪鱼采集并导出网页数据的完整示例。
示例中采集的是赶集网上房产-商铺-深圳-南山分类下的所有商铺信息。
示例网站:/fang6/nanshan/步骤1:创建采集任务1)进入主界面,选择“自定义模式”如何导出网页数据,以赶集网采集为例图22)将要采集的网址URL,复制粘贴到网址输入框中,点击“保存网址”如何导出网页数据,以赶集网采集为例图3步骤2:创建翻页循环1)在页面右上角,打开“流程”,以展现出“流程设计器”和“定制当前操作”两个板块。
将页面下拉到底部,点击“下一页”按钮,在右侧的操作提示框中,选择“循环点击下一页”如何导出网页数据,以赶集网采集为例图4步骤3:创建列表循环1)移动鼠标,选中页面里的第一个商铺链接。
选中后,系统会自动识别页面里的其他相似链接。
在右侧操作提示框中,选择“选中全部”如何导出网页数据,以赶集网采集为例图52)选择“循环点击每个链接”,以创建一个列表循环如何导出网页数据,以赶集网采集为例图6步骤4:提取商铺信息1)在创建列表循环后,系统会自动点击第一个商铺链接,进入商铺详细信息页。
点击需要的字段信息,在右侧的操作提示框中,选择“采集该元素的文本”如何导出网页数据,以赶集网采集为例图72)字段信息选择完成后,选中相应的字段,可以进行字段的自定义命名。
asp.net导出数据到EXCEL的方法总结

导出数据到EXCEL的方法总结在中导出数据到EXCEL里的方法很多,本文总结了常见的几种导出方式(由dataset生成,由datagrid生成,dataview ),供大家参考!1、由dataset生成public void CreateExcel(DataSet ds,string typeid,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="";int i=0;//定义表对象与行对像,同时用DataSet对其值进行初始化DataTable dt=ds.T ables[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(DataRow row in myRow){//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\nfor(i=0;i ls_item +=row[i].ToString() + "\t";ls_item += row[i].T oString() +"\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生成public void ToExcel(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";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/mswordctl.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();}用法:ToExcel(datagrid1);3、这个用dataviewpublic void OutputExcel(DataView dv,string str){//// TODO: 在此处添加构造函数逻辑////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].T oString())).ToString ("yyyy-MM-dd");xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[row Index,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐}elseif(col.DataType == System.Type.GetType("System.String")) {excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].T oString();xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[row Index,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐}else{excel.Cells[rowIndex,colIndex] = row[col.ColumnName].T oString();}}}////加载一个合计行//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[rowSu m,colIndex]).Select();xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSu m,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]).Horizo ntalAlignment = 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]).Border s[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Border s[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colI ndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colI ndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗////显示效果//excel.Visible=true;//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",S heetExportActionEnum.ssExportActionNone,Microsoft.Office.Int erop.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();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.T oString());// 指定返回的是一个不能被客户端读取的流,必须被下载Response.ContentType = "application/ms-excel";// 把文件流发送到客户端Response.WriteFile(file.FullName);// 停止页面的执行Response.End();}本文来自: IT知道网() 详细出处参考:/html/net/aspnet/20091028/6722.html。
.NET中将数据导入(导出)Excel文件

.NET中将数据导出(导出)Excel文件我们在WinForm应用程序或者Web程序中都会遇到需要将DataGridView 或者DataSet中的数据导出成为Excel类型的.xls文件。
下面就通过一个示例向大家演示在WinForm程序中如何将DataGridView中的数据导出为Excel文件,从DataSet中将数据导出为Excel的方法跟这个差不多的,这里就不再介绍了。
?Private void DataGridViewToExcel(DataGridView dgv){SaveFileDialog sfDialog = new SaveFileDialog();//保存导出的excel对话框sfDialog.Filter = "Excel Files(*.xls)|*.xls";//文件过滤器,只能保存为.xls类型的文件sfDialog.CheckFileExists = false;//如果用户指定不存在的文件名是否提示sfDialog.CheckPathExists = false;//如果用户指定不存在的路径是否提示sfDialog.FilterIndex = 0;sfDialog.RestoreDirectory = true;sfDialog.CreatePrompt = true;//如果该文件不存在则提示用户创建新文件sfDialog.Title = "保存为Excel 文件!";if (sfDialog.ShowDialog() == DialogResult.OK){Stream saveStream = sfDialog.OpenFile();//打开要保存的excel文件StreamWriter sw = new StreamWriter(saveStream, Encoding.GetEncoding(-0));//以特定的编码向流中插入字符,GetEncoding(-0)<br>首选编码的代码页标识符。
asp.net生成Excel并导出下载五种实现方法

⽣成Excel并导出下载五种实现⽅法通过GridView(简评:⽅法⽐较简单,但是只适合⽣成格式简单的Excel,且⽆法保留VBA代码),页⾯⽆刷新aspx.cs部分复制代码代码如下:using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Text; public partial class DataPage_NationDataShow : System.Web.UI.Page { private Data_Link link = new Data_Link(); private string sql; protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(DataPage_NationDataShow)); } protected void btnExcel_Click(object sender, EventArgs e) { string strExcelName = "MyExcel"; strExcelName = strExcelName.Replace(@"/", ""); Data_Link link = new Data_Link(); string strSQL = this.hidParam.Value; DataSet ds = new DataSet(); ds = link.D_DataSet_Return(strSQL);//获得想要放⼊Excel的数据 gvExcel.Visible = true; gvExcel.DataSource = null; gvExcel.DataMember = ds.Tables[0].TableName; gvExcel.DataSource = ds.Tables[0]; gvExcel.DataBind(); ExportToExcel(this.Page, gvExcel, strExcelName); } protected void gvExcel_RowDataBound(object sender, GridViewRowEventArgs e) { } public override void VerifyRenderingInServerForm(Control control) { } /// <summary> /// ⼯具⽅法,Excel出⼒(解决乱码问题) /// </summary> ///<param name="page">调⽤页⾯</param> /// <param name="excel">Excel数据</param> /// <param name="fileName">⽂件名</param> public void ExportToExcel(System.Web.UI.Page page, GridView excel, string fileName) { try { foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } } excel.Font.Size = 10; excel.AlternatingRowStyle.BackColor =System.Drawing.Color.LightCyan; excel.RowStyle.Height = 25; page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); page.Response.Charset = "utf-8"; page.Response.ContentType = "application/vnd.ms-excel"; page.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");excel.Page.EnableViewState = false; excel.Visible = true; excel.HeaderStyle.Reset(); excel.AlternatingRowStyle.Reset(); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); excel.RenderControl(oHtmlTextWriter);page.Response.Write(oStringWriter.ToString()); page.Response.End(); excel.DataSource = null; excel.Visible = false; } catch (Exception e) { } } }aspx部分复制代码代码如下:<head runat="server"> <script type="text/javascript"> //Excel DownLoad function excelExport(){ var hidText = document.getElementById("hidParam"); hidText.value = "some params"; document.getElementById("ExcelOutput").click(); } </script> </head> <body onload="pageInit()"> <form id="form1"runat="server"> <input type="button" value="EXCEL下载" style="width:100px;" onclick="excelExport()" id="excelBut" /><input id="hidParam" type="text" runat="server" style="display:none;"/> <asp:Button runat="server" ID="ExcelOutput"style="display:none" Text= "EXCEL出⼒" Width="0px" onclick="btnExcel_Click" UseSubmitBehavior="false"/><asp:GridView ID="gvExcel" runat="server" Height="95px" OnRowDataBound="gvExcel_RowDataBound" Visible="False"> </asp:GridView> </form> </body>在刚才的aspx.cs代码中复制代码代码如下:foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } }这部分是给表头添加样式。
.net把datatable导出到excel

.net把datatable导出到exceldsResult = BaseClass.Query(sql);#region 用NPOI方式导出,数据量过多则抛出内存溢出异常//using (System.IO.MemoryStream ms = Util.DataSetToExcel(dsResult))//{// string pathtmp = folder + name + ".xlsx";// using (System.IO.FileStream fs = new System.IO.FileStream(pathtmp, System.IO.FileMode.Create, System.IO.FileAccess.Write))// {// byte[] data = ms.ToArray();// fs.Write(data, 0, data.Length);// fs.Flush();// }//}#endregion//用数据流的方式导出//string path = folder + name + ".xlsx";//ExcelUtil.ExportT oExcel(dsResult.Tables[0], path);//用EPPlus.dll导出Excel(xlsx)string path = folder + name + ".xlsx";ExcelExport.ExportByEPPlus(table,dsResult.Tables[0], path);using System.Data;using System.IO;using erModel;using erModel;using erModel;using NPOI;using NPOI.HPSF;using NPOI.HSSF;using NPOI.HSSF.Util;using NPOI.POIFS;using NPOI.SS.Formula.Eval;using NPOI.Util;using NPOI.SS;using NPOI.DDF;using NPOI.SS.Util;using System.Collections;using System.Text.RegularExpressions;using NPOI.XSSF;using System.Text;using OfficeOpenXml;using OfficeOpenXml.Style;namespace Cis.DRGsSystem.Dal{/// <summary>/// 用NPOI插件导出Excel,如果数据量过大则抛内存溢出错误,改用数据流的方式导出Excel/// </summary>public static class Util{/// <summary>/// 拆分字符串1,2,3,4,5/// </summary>/// <param name="strid">1,2,3,4,5</param>/// <returns></returns>public static string StrArr(this string strid){string StrValue = "";if (!string.IsNullOrEmpty(strid)){string[] strarr = strid.Split(',');foreach (string item in strarr){StrValue += "'" + item.Trim() + "',";}StrValue = StrValue.Substring(0, StrValue.Length - 1);}return StrValue;}#region DataSet导出到Excel/// <summary>/// DataSet导出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataSet</param> public static MemoryStream DataSetToExcel(DataSet ds) {XSSFWorkbook workbook = new XSSFWorkbook();for (int k = 0; k < ds.Tables.Count; k++){// HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(ds.Tables[k].TableName.ToStr ing());#region 右击文件属性信息{DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();pany = "NPOI";// workbook.DocumentSummaryInformation = dsi;SummaryInformation si = PropertySetFactory.CreateSummaryInformation();si.Author = "文件作者信息"; //填加xls文件作者信息si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息stAuthor = "最后保存者信息"; //填加xls文件最后保存者信息ments = "作者信息"; //填加xls文件作者信息si.Title = "标题信息"; //填加xls文件标题信息si.Subject = "主题信息";//填加文件主题信息si.CreateDateTime = System.DateTime.Now;}#endregionXSSFCellStyle dateStyle = (XSSFCellStyle)workbook.CreateCellStyle();XSSFDataFormat format = (XSSFDataFormat)workbook.CreateDataFormat();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");//取得列宽int rowIndex = 0;foreach (DataRow row in ds.Tables[k].Rows){#region 新建表,填充表头,填充列头,样式if (rowIndex == 0){#region 列头及样式{XSSFRow headerRow = (XSSFRow)sheet.CreateRow(0);XSSFCellStyle headStyle = (XSSFCellStyle)workbook.CreateCellStyle();//headStyle.Alignment = CellHorizontalAlignment.CENTER;XSSFFont font = (XSSFFont)workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 700;headStyle.SetFont(font);foreach (DataColumn column in ds.T ables[k].Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column. ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//设置列宽//sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);}}#endregionrowIndex = 1;}#endregion#region 填充内容XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);foreach (DataColumn column in ds.T ables[k].Columns){XSSFCell newCell = (XSSFCell)dataRow.CreateCell(column.Ordinal);newCell.SetCellType(CellType.String);string drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串类型newCell.SetCellValue(drValue);break;case "System.DateTime"://日期类型System.DateTime dateV;System.DateTime.TryParse(drValue, out dateV);newCell.SetCellValue(dateV);newCell.CellStyle = dateStyle;//格式化显示break;case "System.Boolean"://布尔型bool boolV = false;bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break;case "System.Decimal"://浮点型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break;case "System.DBNull"://空值处理newCell.SetCellValue("");break;default:newCell.SetCellValue("");break;}}#endregionrowIndex++;}}using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);ms.Flush();return ms;}}#endregion}/// <summary>/// 用数据流方式导出Excel/// </summary>public class ExcelUtil{/// <summary>/// 导出文件,使用文件流。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
public void CreateExcel(DataSet ds,string typeid,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="";int i=0;//定义表对象与行对像,同时用DataSet对其值进行初始化DataTable dt=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(DataRow row in myRow){//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\nfor(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();}public void ToExcel(System.Web.UI.Control ctl){HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Exce l.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 = 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();}用法:ToExcel(datagrid1);//3、这个用dataviewpublic void OutputExcel(DataView dv,string str){//// TODO: 在此处添加构造函数逻辑////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]).HorizontalAlignmen t = 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[rowIndex,colIndex]).HorizontalAlignmen t = 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.xlEdg eRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdg eBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗////显示效果//excel.Visible=true;//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActi onNone,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();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();}。