asp.net里导出excel表方法汇总

合集下载

Asp.Net使用Npoi导入导出Excel的方法

Asp.Net使用Npoi导入导出Excel的方法

使⽤Npoi导⼊导出Excel的⽅法针对Excel⽂件的导⼊与导出是⾮常常见的功能之⼀。

本⽂实例讲述了使⽤Npoi导⼊导出Excel的⽅法。

分享给⼤家供⼤家参考之⽤。

具体⽅法如下:在使⽤Npoi导出Excel的时候,服务器可以不装任何office组件,⼀般在导出时⽤到Npoi导出Excel⽂件,所导Excel也符合规范,打开时也不会有任何⽂件损坏之类的提⽰。

但是在做导⼊时还是使⽤OleDb的⽅式,这种⽅式的导⼊在服务器端似乎还是需要装office组件的。

⼀、Npoi导出/下载Excel具体功能代码如下:public void NpoiExcel(DataTable dt, string title){erModel.HSSFWorkbook book = new erModel.HSSFWorkbook();erModel.ISheet sheet = book.CreateSheet("Sheet1");erModel.IRow headerrow = sheet.CreateRow(0);ICellStyle style = book.CreateCellStyle();style.Alignment = HorizontalAlignment.Center;style.VerticalAlignment = VerticalAlignment.Center;for (int i = 0; i < dt.Columns.Count; i++){ICell cell = headerrow.CreateCell(i);cell.CellStyle = style;cell.SetCellValue(dt.Columns[i].ColumnName);}MemoryStream ms = new MemoryStream();book.Write(ms);Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8))); Response.BinaryWrite(ms.ToArray());Response.End();book = null;ms.Close();ms.Dispose();}⼆、导⼊Excel导⼊仍然是⽤OleDb这种⽅式,感兴趣的朋友可以尝试⼀下其他⽅法。

怎么将ASP.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文件这里不是重点,故跳过。

asp.net中使用npoi导出excel电子表格

asp.net中使用npoi导出excel电子表格

中使用npoi导出excel电子表格NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目,可以在没有安装Office的情况下对Word或Excel文档进行读写操作。

一、添加引用1、将NPOI.dll、Ioniz.Zip.dll复制到web/bin 文件夹中;2、在common公用工具层添加引用,浏览找到NPOI.dll;二、类库代码在common中建立类库NPOIExcel.csusing System;using System.Collections.Generic;using System.Linq;using System.Web;using NPOI;using NPOI.HPSF;using NPOI.HSSF;using erModel;using NPOI.POIFS;using NPOI.Util;using System.IO;using System.Data;using System.Data.SqlClient;public class DataTableRenderT oExcel{/// <summary>/// DataTable导出到Excel文件/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>/// <param name="strFileName">保存位置</param>public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string strFileName){using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText)){using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)){byte[] data = ms.T oArray();fs.Write(data, 0, data.Length);fs.Flush();}}}/// <summary>/// DataTable导出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>public static MemoryStream DataTableToExcel(DataT able dtSource, string strHeaderText){HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();#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;workbook.SummaryInformation = si;}#endregionHSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");//取得列宽int[] arrColWidth = new int[dtSource.Columns.Count];foreach (DataColumn item in dtSource.Columns){arrColWidth[item.Ordinal] = System.Text.Encoding.GetEncoding(936).GetBytes(item.Column Name.T oString()).Length;}for (int i = 0; i < dtSource.Rows.Count; i++){for (int j = 0; j < dtSource.Columns.Count; j++){int intTemp = System.Text.Encoding.GetEncoding(936).GetBytes(dtSource.Row s[i][j].ToString()).Length;if (intTemp > arrColWidth[j]){arrColWidth[j] = intTemp;}}}int rowIndex = 0;foreach (DataRow row in dtSource.Rows){#region 新建表,填充表头,填充列头,样式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = (HSSFSheet)workbook.CreateSheet();}#region 表头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(strHeaderText);HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();headStyle.Alignment = erModel.HorizontalAlignment.LEFT; //左对齐HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 20;font.Boldweight = 700;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));//headerRow.Dispose();}#endregion#region 列头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();//headStyle.Alignment = CellHorizontalAlignment.CENTER;HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 700;headStyle.SetFont(font);foreach (DataColumn column in dtSource.Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//设置列宽sheet.SetColumnWidth(column.Ordinal,(arrColWidth[column.Ordinal] + 1) * 256);}// headerRow.Dispose();}#endregionrowIndex = 2;}#endregion#region 填充内容HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);foreach (DataColumn column in dtSource.Columns){HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);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();ms.Position = 0;sheet.Dispose();//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheetreturn ms;}}/// <summary>读取excel/// 默认第一行为标头/// </summary>/// <param name="strFileName">excel文档路径</param> /// <returns></returns>public static DataT able Import(string strFileName){DataTable dt = new DataTable();HSSFWorkbook hssfworkbook;using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)){hssfworkbook = new HSSFWorkbook(file);}HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);System.Collections.IEnumerator rows = sheet.GetRowEnumerator();HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);int cellCount = stCellNum;for (int j = 0; j < cellCount; j++){HSSFCell cell = (HSSFCell)headerRow.GetCell(j);dt.Columns.Add(cell.ToString());}for (int i = (sheet.FirstRowNum + 1); i <= stRowNum; i++){HSSFRow row = (HSSFRow)sheet.GetRow(i);DataRow dataRow = dt.NewRow();for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null)dataRow[j] = row.GetCell(j).ToString();}dt.Rows.Add(dataRow);}return dt;}//以上是新增的。

asp.net导出数据到EXCEL的方法总结

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。

asp.net中导出excel数据的方法汇总

asp.net中导出excel数据的方法汇总

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.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();}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、这个用dataview代码如下:public 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]).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[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.xledg eright].weight = xlborderweight.xlthick;//设置右边线加粗xst.get_range(excel.cells[rowsum,2],excel.cells[rowsum,colindex]).borders[xlbordersindex.xledge bottom].weight = xlborderweight.xlthick;//设置下边线加粗////显示效果//excel.visible=true;//xst.export(server.mappath(.)++this.xlfile.text+.xls,sheetexportactionenum.ssexportactionnone,microsoft.office.interop.owc.sheetexportformat.ssexpo rthtml);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();}导入、导出excel中的一些问题汇总一、在项目中的添加引用:右击项目资源管理器的引用--&gt;添加引用--&gt;选择.net选项卡--&gt;选择microsoft.office.interop.excel--&gt;确定(如下图);在选择时注意一下.net组件的版本号,图是的12.0.0.0是office2007的版本:二、在项目中使用microsoft.office.interop.excel:如果想使用microsoft.office.interop.excel,首先需要在项目中引用命名空间:using microsoft.office.interop.excel;三、建立excel.application相关对象//建立application对象microsoft.office.interop.excel.application myexcel = new application();//建立workbooks对象workbooks mybooks = myexcel.application.workbooks;//建立一个system.reflection.missing的object对象object omissing = system.reflection.missing.value;四、打开或新建excel的book文件//打开excel文件,注意里的“exccelfilepath”为excel文件在服务器上的物理地址,包括文件名workbook mybook = mybooks.open(exccelfilepath,omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing);//新建workseet对象,,此处为要操作的工作表,当前要操作的工作表的获取方法有两种:使用工作表的索引值或使用工作表的名称,名称默认为:“sheet1”/“sheet2”等worksheet mysheet = (worksheet)mybook.worksheets[1];//如果是新建excel工作簿,需要设置如下两行内容,以保证工作簿中有一个工作表,workbook workbook1 = excel1.workbooks.add(true);worksheet mysheet= (worksheet)workbook1.worksheets[sheet1];//设置excel对象是否显示界面,默认为false不显示界面myexcel.visble=true;五、一些比较重要的针对excel的操作1、获取range对象①、获取一个单元格的range对象://选择第一行、第一列的单元的单元格为range对象range r = (excel.range)mysheet.cells[1, 1];//选择多个连续的单元格为range对象range r=(excel.range)range.get_range(a1:f3)②、给单元格赋值或取出单元格的值://已选择了range对象的赋值:r.text=中国;//未选择range对象的赋值:mysheet.cells[1,2].text=中国;//已选择了range对象的取值:string strvalue= r.text;//未选择range对象的取值:string strvalue= mysheet.cells[1,2].text;③、给单元格设置边框mysheet.cells[2, 1].borderaround(xllinestyle.xlcontinuous, xlborderweight.xlthin, xlcolorindex.xlcolorindexautomatic, null);//画线④、合并单元格//合并单元格前先要将要合并的单元格选择为range对象range r=range.get_range(a1:f3);//然后现设置合并单元格r.mergecells = true;⑤、设置单元格的字体、字号、背景色等属性mysheet.cells[1, 1] = 黑体;mysheet.cells[1, 1].font.size = 20;mysheet.rows[1:1].rowheight = 40;mysheet.cells[1, 1].interior.color = color.fromargb(224, 224, 224);//设置颜色⑥、删除一行://首先获取要删除的行的rangemicrosoft.office.interop.excel.range range = (microsoft.office.interop.excel.range)mysheet.rows[sendedrow[1], type.missing];//注意删除行后删除后的行号被下面的行替换,如果逐行删除,请先从最大的行号往最小的行号删除range.delete(microsoft.office.interop.excel.xldeleteshiftdirection.xlshiftup);⑦、获取有数据的行数int rowsint = edrange.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操作的方法private void killexcel(){outputexcel();gc.collect();gc.waitforpendingfinalizers();}好多网友都在介绍使用gc.collect()释放excel占用的资源来结束excel进行,如果将“gc.collect();”与操作excel的业务写在一个程序块中,“gc”是永远不能结束excel进程的,在web应用程序中,这种现象是很可怕的事情。

Asp.NetCore实现Excel导出功能的实现方法

Asp.NetCore实现Excel导出功能的实现方法

Core实现Excel导出功能的实现⽅法⽬录安装 ClosedXML将数据导出成 CSV ⽂件将数据导出成 XLSX ⽂件下载 Excel在web应⽤程序开发时,或许你会遇到这样的需求,如何在 Core 中实现 excel 或者 word 的导⼊导出,在 NuGet 上有⼤量的⼯具包可以实现这样的功能,本篇就讨论下如何使⽤ ClosedXML 实现 Excel 数据导出。

安装 ClosedXML如果想实现 Excel 的导出功能,在 Core 中有很多的dll可以做到,其中的⼀个叫做 ClosedXML,你可以通过可视化界⾯ NuGet package manager 去安装,也可以使⽤命令⾏ NuGet package manager console 执⾏下⾯命令。

Install-Package ClosedXML将数据导出成 CSV ⽂件将数据导成 CSV ⽂件是⾮常简单的,毕竟每⾏数据都是⽤ , 隔开即可,可以⽤ NuGet 上的 CsvExport 或者AWright18.SimpleCSVExporter 去实现,当然你觉得⾃⼰很 ,可以亲⾃操⼑实现,下⾯我准备亲⾃实现⼀下,先看下⾯定义的 Author 类。

public class Author{public int Id { get; set; }public string FirstName { get; set; }public string LastName { get; set; }}然后塞⼀些数据到 authors 列表中,如下代码所⽰:List<Author> authors = new List<Author>{new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" },new Author { Id = 2, FirstName = "Steve", LastName = "Smith" },new Author { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}};定义⼀个 DownloadCommaSeperatedFile ⽅法,⽤于实现 Action 的 csv 导出功能。

ASP.NET使用GridView导出Excel实现方法

ASP.NET使用GridView导出Excel实现方法

使⽤GridView导出Excel实现⽅法本⽂实例讲述了使⽤GridView导出Excel实现⽅法。

分享给⼤家供⼤家参考。

具体实现⽅法如下:复制代码代码如下:/// <summary>/// 将DataTable数据导出到EXCEL,调⽤该⽅法后⾃动返回可下载的⽂件流/// </summary>/// <param name="dtData">要导出的数据源</param>public static void DataTable1Excel(System.Data.DataTable dtData){System.Web.UI.WebControls.GridView gvExport = null;// 当前对话System.Web.HttpContext curContext = System.Web.HttpContext.Current;// IO⽤于导出并返回excel⽂件System.IO.StringWriter strWriter = null;System.Web.UI.HtmlTextWriter htmlWriter = null;if (dtData != null){// 设置编码和附件格式curContext.Response.ContentType = "application/vnd.ms-excel";curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");curContext.Response.Charset = "utf-8";// 导出excel⽂件strWriter = new System.IO.StringWriter();htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);// 为了解决gvData中可能进⾏了分页的情况,需要重新定义⼀个⽆分页的GridViewgvExport = new System.Web.UI.WebControls.GridView();gvExport.DataSource = dtData.DefaultView;gvExport.AllowPaging = false;gvExport.DataBind();// 返回客户端gvExport.RenderControl(htmlWriter);curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />" + strWriter.ToString());curContext.Response.End();}}/// <summary>/// 直接输出Excel/// </summary>/// <param name="dtData"></param>public static void DataTable2Excel(System.Data.DataTable dtData){ System.Web.UI.WebControls.DataGrid dgExport = null; // 当前对话 System.Web.HttpContext curContext = System.Web.HttpContext.Current; // IO⽤于导出并返回excel⽂件 System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (dtData != null) { // 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding =System.Text.Encoding.UTF8; curContext.Response.Charset = ""; // 导出excel⽂件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); // 为了解决dgData中可能进⾏了分页的情况,需要重新定义⼀个⽆分页的DataGrid dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); }}希望本⽂所述对⼤家的程序设计有所帮助。

在ASP中怎么把页面中的数据导出到EXCEL

在ASP中怎么把页面中的数据导出到EXCEL

使用asp怎样将数据导出到excel文件 Web注意:两个函数中的“data“是网页中要导出的table的 id<input type="hidden" name="out_word" onclick="vbscript:buildDoc" value="导出到word" class="notPrint"><input type="hidden" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint">导出到Excel代码<SCRIPT LANGUAGE="JavaScript"><!--function AutomateExcel(){// Start Excel and get Application object.var oXL = new ActiveXObject("Excel.Application");// Get a new workbook.var oWB = oXL.Workbooks.Add();var oSheet = oWB.ActiveSheet;var table = document.all.data;var hang = table.rows.length;var lie = table.rows(0).cells.length;// Add table headers going cell by cell.for (i=0;i<hang;i++){for (j=0;j<lie;j++){oSheet.Cells(i+1,j+1).Value = table.rows(i).cells(j).innerText;}}oXL.Visible = true;erControl = true;}//--></SCRIPT>导出到Word代码<script language="vbscript">Sub buildDocset table = document.all.datarow = table.rows.lengthcolumn = table.rows(1).cells.lengthSet objWordDoc = CreateObject("Word.Document")'objWordDoc.Application.Documents.Add theTemplate, FalseobjWordDoc.Application.Visible=TrueDim theArray(20,10000)for i=0 to row-1for j=0 to column-1theArray(j+1,i+1) = table.rows(i).cells(j).innerTEXTnextnextobjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("综合查询结果集") //显示表格标题objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("") Set rngPara = objWordDoc.Application.ActiveDocument.Paragraphs(1).Range With rngPara.Bold = True //将标题设为粗体.ParagraphFormat.Alignment = 1 //将标题居中 = "隶书" //设定标题字体.Font.Size = 18 //设定标题字体大小End WithSet rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).RangeSet tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)for i = 1 to columnobjWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.InsertAfter theArray(i,1)objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Paragraph Format.alignment=1nextFor i =1 to columnFor j = 2 to rowobjWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.InsertAfter theArray(i,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Paragraph Format.alignment=1NextNextEnd Sub</SCRIPT>在ASP中怎么把页面中的数据导出到EXCEL直接读SQL库,我想也可以用来解决你的问题,(同理:页面上显示的内容当然也是读库的,除非你是静态的那算了)<!--#include file="../opendb.asp"--><!--写链接的事不用我弄了吧?--><title>生成报表</title><%dim conn,strconnset conn=server.CreateObject("adodb.connection")conn.Open ConnStrdim rs,sql,filename,fs,myfile,xSet fs = server.CreateObject("scripting.filesystemobject")filepath=Request.ServerVariables("APPL_PHYSICAL_PATH")filename = filepath&"temp_xls\"&year(now)&month(now)&day(now)&".xls"if fs.FileExists(filename) thenfs.DeleteFile(filename)end ifset myfile = fs.CreateTextFile(filename,true)Set rs = Server.CreateObject("ADODB.Recordset")sql = "select * from jdxx"rs.Open sql,conn,1,1if rs.EOF and rs.BOF thenelsedim strLine,responsestrstrLine=""For each x in rs.fieldsstrLine = strLine & & chr(9)Nextmyfile.writeline strLineDo while Not rs.EOFstrLine=""for each x in rs.FieldsstrLine = strLine & x.value & chr(9)nextmyfile.writeline strLiners.MoveNextloopend ifrs.Closeset rs = nothingremotefile="http://xxx.xxx.x.xxx/temp_xls/"&year(now)&month(now)&day(now)&".xls" response.write "<font size=2 color=blue>报表巳生成,<a href="&remotefile&">请点击这里下载该报表!</a></font>"%>在ASP中怎么把页面中的数据导出到EXCEL<%@ LANGUAGE="VBSCRIPT" CODEPAGE="950"%><%'關鍵所在Response.ContentType = "application/vnd.ms-excel"Set conn=Server.CreateObject("ADODB.Connection")Set rs=Server.CreateObject("ADODB.Recordset")strconn = "Provider = SQLOLEDB; Data Source = 192.168.0.2; Uid=gt_bbs;Pwd=gt_bbs;DataBase=gt_bbs"conn.open strconnSQL="Select top 100 id,uid,uer,bm,zw,zb,gxrq,ip,be From Gt_user order by id desc"rs.Open SQL,conn,3,1if rs.eof and rs.bof thenResponse.Write"<div align=center><br>沒有任何記錄</div>"else%><TABLE cellSpacing=0 cellPadding=0 width="100%" border=1><TR><TD width=12% height="25" class=borderon>&nbsp;代 </TD> <TD width="11%" class=borderon>&nbsp; 名</TD><TD width="11%" class=borderon>&nbsp;部門</TD><TD width="14%" class=borderon>&nbsp; </TD><TD width="6%" class=borderon>&nbsp; 別</TD><TD width="16%" class=borderon>&nbsp; 登</TD><TD width="16%" class=borderon>&nbsp; 登 IP</TD> </TR></TABLE><TABLE width="100%" border=1 cellPadding=0 cellSpacing=0><%do while (Not RS.Eof) and (I<RS.PageSize)%><TR bgcolor=<%=bg2%>><TD class=all width=12% height=20 >&nbsp;<%=rs(1)%></TD> <TD width="11%" class=all>&nbsp;<%=rs(2)%></TD><TD width="11%" class=all>&nbsp;<%=rs(3)%></TD><TD width="14%" class=all>&nbsp;<%=rs(4)%></TD><TD width="6%" class=all>&nbsp;<%=rs(5)%></TD><TD width="16%" class=all>&nbsp;<%=rs(6)%></TD><TD width="16%" class=all>&nbsp;<%=rs(7)%></TD></TR><%Rs.MoveNextLoopend IFSet Conn = NothingSet Rs = Nothing%></TABLE>。

ASPNET中实现EXCEL导入和导出

ASPNET中实现EXCEL导入和导出

ASPNET中实现EXCEL导入和导出页面效果图如下:录入按钮的OnClick事件代码如下:protectedvoid btnInput_Click(object sender, EventArgs e){if (fpInput.HasFile)//fpInput为FileUpload控件,判断是否选择了文件{string fileExt =System.IO.Path.GetExtension(fpInput.FileName);//获取文件名的后缀if (fileExt == ".xls")//判断文件后缀名是否是xls{try{string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fpInput.PostedFile.FileName + ";Extended Properties=Excel8.0;";//以xls文件创建连接字符串OleDbConnection conn = new OleDbConnection(strConn); OleDbDataAdapter oada = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);oada.Fill(dstInput_JWTYBH, "xlsTable");//填充xls中数据到数据集DataTable dtJWTYBH = dstInput_JWTYBH.Tables["xlsTable"];for (int i = 0; i < dtJWTYBH.Rows.Count;i++)//循环读取xls文件中的数据{strSql = "SELECT COUNT(*) FROM XS_JBXX WHERE XS_XH="" + dstInput_JWTYBH.Tables["xlsTable"].Rows[i]["学号"].ToString() + """;int iStNum = Convert.ToInt32(db.ExecScalar(strSql));if (iStNum == 0){strSql = "INSERT INTO XS_JBXX(XS_XH,XS_SFZH,XS_XM,NJ_ID,BJ_BH,XS_XBM,XS_XJH) VALUES("+ """ + dtJWTYBH.Rows[i]["学号"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["身份证号"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["姓名"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["年级编号"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["班级编号"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["性别码"].ToString() + "","+ """ + dtJWTYBH.Rows[i]["教委统一编号"].ToString() + "")";}else if (iStNum == 1){strSql = "UPDATE XS_JBXX SET "+ "XS_SFZH="" + dtJWTYBH.Rows[i]["身份证号"].ToString() + "","+ "XS_XM="" + dtJWTYBH.Rows[i]["姓名"].ToString() + "","+ "NJ_ID="" + dtJWTYBH.Rows[i]["年级编号"].ToString() + "", " + "BJ_BH="" + dtJWTYBH.Rows[i]["班级编号"].ToString() + "", " + "XS_XBM="" + dtJWTYBH.Rows[i]["性别码"].ToString() + "", "+ "XS_XJH="" + dtJWTYBH.Rows[i]["教委统一编号"].ToString() + "" "+ "WHERE XS_XH="" + dtJWTYBH.Rows[i]["学号"].ToString() + """;}db.ExecCommand(strSql);BindData();}}catch (Exception exp){Response.Write("系统出现以下错误:" +exp.Message +"!请尽快与管理员联系.");}finally{db.Close();}}else{Response.Write("");}}Excel文件的导入在中比较简单,主要的要点是FileUpload控件的使用和用OleDb连接物理xls文件.对xls文件中数据的操作同对DataSet中数据的操作是一样的..下面是对导出功能的实现:先定义一个导出函数/////Excel数据导出函数//////<param< p=""> </param<>name="ctl">需要导出数据的控件///<param< p=""> </param<>name="FileName">导出的Excel文件名private voidToExcel(Control ctl, string FileName)HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("GB2312");HttpContext.Current.Response.Charset = "GB2312";HttpContext.Current.Response.ContentType ="application/ms-excel";HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + "" + FileName);ctl.Page.EnableViewState = false;System.IO.StringWriter tw = new System.IO.StringWriter();HtmlTextWriter hw = new HtmlTextWriter(tw);ctl.RenderControl(hw);HttpContext.Current.Response.Write(tw.ToString());HttpContext.Current.Response.End();}其中一下两行代码最为重要HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("GB2312");HttpContext.Current.Response.Charset = "GB2312";因为使用GB2312可以解决Excel导出数据出现中文乱码的问题,使用UTF-7/8都会出现乱码.导出按钮的OnClick事件如下:protectedvoid btnOutput_Click(object sender, EventArgs e)gvStJWTYBJ.AllowPaging = false;//设置GridView控件不能分页gvStJWTYBJ.AllowSorting = false;//设置GridView控件不能排序BindData();ToExcel(gvStJWTYBJ, "JWTYBH.xls");gvStJWTYBJ.AllowPaging = true;//恢复GridView控件分页gvStJWTYBJ.AllowSorting =true;//恢复GridView控件排序BindData();//数据绑定函数}如果在页面显示的时候设置了GridView控件是可以分页和排序的则再Excel数据导出的时候就∙分享微经验,让更多的人受益∙快去分享吧!!!只能导出显示的那几条数据而不能导出所有的数据,所以在调用ToExcel()函数进行Excel导出的时候要先设置GridView的排序和分页为false.以上代码还不能实现Excel的数据导出,因为会报以下两个错误.1.类型“GridView”的控件“gvStJWTYBJ”必须放在具有 runat=server 的窗体标记内。

asp.net生成Excel并导出下载五种实现方法

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; } }这部分是给表头添加样式。

ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单⽅法我在做⼀项⽬时,客户要求要将从数据库中获取数据后的ASP页⾯导出成EXCEL或WORD⽂档。

经本⼈试验后找出了最简单的⽅法:在ASP⽂件的最开头位置加⼊下⾯的代码就可以了,⾮常简单。

Asp代码1. EXCEL2. <%3. Response.ContentType ="application/vnd.ms-excel"4. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络表格.xls"5. %>6.7. WORD8. <%9. Response.ContentType ="application/vnd.ms-word"10. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络⽂档.doc"11. %>导出为WORD时,若⽂档中含有表格,需要打打印,则要在导出的页⾯中加⼊下⾯的样式。

Css代码1. <style type="text/css">2. <!--3. table{4. border-collapse:collapse;border:none;mso-border-alt:solid windowtext .5pt;5. mso-yfti-tbllook:480;mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-border-insideh:6. .5pt solid windowtext;mso-border-insidev:.5pt solid windowtext;border-left:solid windowtext 1.0pt;border-top:solid windowtext 1.0pt;7. }8. td{9. border-top:none;border-left:10. none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;11. mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;12. mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;13. }14. -->15. </style>我打字系统项⽬中的⼀个导出为EXCEL⽂件的实例代码如下:Asp代码1. <!--#include file="hbwlConfig.asp" -->2. <%Response.ContentType ="application/vnd.ms-excel"3. Response.AddHeader "Content-Disposition", "attachment; filename=chengji.xls"%>4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">5. <html xmlns="/1999/xhtml">6. <head>7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />8. <title>打字成绩</title>9. <style type="text/css">10. .tableWg {border:1px solid #9bbde6;}11. .tableWg tr{text-align:center;}12. .tableWg td{ border-bottom:1px dotted #9bbde6; border-right:1px dotted #9bbde6;}13. </style>14. </head>15. <body>16. <%sql=session("chengjisql")17. response.Write hbwl.dbSelect(sql,0,1,"",0,"",0,"tableWg")%>18. </body>19. </html>20. <%set hbwl=nothing%>。

将asp中把数据导出为excel

将asp中把数据导出为excel

将asp中把数据导出为excel我们在做项目的时候经常要将数据库的数据导出到excel中,很多asp用户并不知道怎么写,下面小编告诉你们两个能将asp导入excel 的方法,希望对你有帮助!将asp中数据导出为excel方法一:使用文件组件1 < %2 dim s,sql,filename,fs,myfile,x34 Set fs = server.CreateObject("scripting.filesystemobject")5 '--假设你想让生成的EXCEL文件做如下的存放6 filename = Server.MapPath("order.xls")7 '--如果原来的EXCEL文件存在的话删除它8 if fs.FileExists(filename) then9 fs.DeleteFile(filename)10 end if11 '--创建EXCEL文件12 set myfile = fs.CreateTextFile(filename,true)131415 StartTime = Request("StartTime")16 EndTime = Request("EndTime")17 StartEndTime = "AddTime between #"& StartTime &" 00:00:00# and #"& EndTime &" 23:59:59#"18 strSql = "select * from mksuers "19 Set rstData =conn.execute(strSql)20 if not rstData.EOF and not rstData.BOF then2122 dim trLine,responsestr23 strLine=""24 For each x in rstData.fields25 strLine = strLine & & chr(9)26 Next2728 '--将表的列名先写入EXCEL29 myfile.writeline strLine3031 Do while Not rstData.EOF32 strLine=""3334 for each x in rstData.Fields35 strLine = strLine & x.value & chr(9)36 next37 myfile.writeline strLine3839 rstData.MoveNext40 loop4142 end if43 Response.Write "生成EXCEL文件成功,点击<a href="/" rel="external nofollow" order.xls"" target=""_blank"">下载!"44 rstData.Close45 set rstData = nothing46 Conn.Close47 Set Conn = nothing48 %>将asp中数据导出为excel方法二:用excel组件1 < %2 set rs=server.createobject("adodb.recordset")3 sql="select * from mkusers"4 rs.open sql,objconn,1,15 Set ExcelApp =CreateObject("Excel.Application")6 ExcelApp.Application.Visible = True7 Set ExcelBook = ExcelApp.Workbooks.Add8 ExcelBook.WorkSheets(1).cells(1,1).value ="用户表"9 ExcelBook.WorkSheets(1).cells(2,1).value = "用户编号"10 ExcelBook.WorkSheets(1).cells(2,2).value = "登陆名"11 ExcelBook.WorkSheets(1).cells(2,3).value = "真实姓名"12 ExcelBook.WorkSheets(1).cells(2,4).value = "密码"13 cnt =314 do while not rs.eof15 ExcelBook.WorkSheets(1).cells(cnt,1).value = rs("provinceid")16 ExcelBook.WorkSheets(1).cells(cnt,2).value = rs("province")17 ExcelBook.WorkSheets(1).cells(cnt,3).value = rs("flag")18 ExcelBook.WorkSheets(1).cells(cnt,4).value = rs("id")19 rs.movenext20 cnt = cint(cnt) + 121 loop22 Excelbook.SaveAs "d:\yourfile.xls" '这个是数据导出完毕以后在D盘存成文件23 ExcelApp.Application.Quit '导出以后退出Excel24 Set ExcelApp = Nothing '注销Excel对象25 %>< %26 set rs=server.createobject("adodb.recordset")27 sql="select * from mkusers"28 rs.open sql,objconn,1,129 Set ExcelApp =CreateObject("Excel.Application")30 ExcelApp.Application.Visible = True31 Set ExcelBook = ExcelApp.Workbooks.Add32 ExcelBook.WorkSheets(1).cells(1,1).value ="用户表"33 ExcelBook.WorkSheets(1).cells(2,1).value = "用户编号"34 ExcelBook.WorkSheets(1).cells(2,2).value = "登陆名"35 ExcelBook.WorkSheets(1).cells(2,3).value = "真实姓名"36 ExcelBook.WorkSheets(1).cells(2,4).value = "密码"37 cnt =338 do while not rs.eof39 ExcelBook.WorkSheets(1).cells(cnt,1).value = rs("provinceid")40 ExcelBook.WorkSheets(1).cells(cnt,2).value = rs("province")41 ExcelBook.WorkSheets(1).cells(cnt,3).value = rs("flag")42 ExcelBook.WorkSheets(1).cells(cnt,4).value = rs("id")43 rs.movenext44 cnt = cint(cnt) + 145 loop46 Excelbook.SaveAs "d:\yourfile.xls" '这个是数据导出完毕以后在D盘存成文件47 ExcelApp.Application.Quit '导出以后退出Excel48 Set ExcelApp = Nothing '注销Excel对象49%>猜你喜欢:。

ASP导出Excel数据的四种方法

ASP导出Excel数据的四种方法

ASP导出Excel数据的四种方法一、使用OWC什么是OWC?OWC是Office Web Compent的缩写,即Microsoft的Office Web组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。

在一个intranet环境中,如果可以假设客户机上存在特定的浏览器和一些功能强大的软件(如IE5和Office 2000),那么就有能力利用Office Web组件提供一个交互式图形开发环境。

这种模式下,客户端工作站将在整个任务中分担很大的比重。

<%Option ExplicitClass ExcelGenPrivate objSpreadsheetPrivate iColOffsetPrivate iRowOffsetSub Class_Initialize()Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet")iRowOffset = 2iColOffset = 2End SubSub Class_Terminate()Set objSpreadsheet = Nothing "Clean up End SubPublic Property Let ColumnOffset(iColOff) If iColOff > 0 theniColOffset = iColOffElseiColOffset = 2End IfEnd PropertyPublic Property Let RowOffset(iRowOff) If iRowOff > 0 theniRowOffset = iRowOffElseiRowOffset = 2End IfEnd Property Sub GenerateWorksheet(objRS)"Populates the Excel worksheet based on a Recordset"s contents"Start by displaying the titlesIf objRS.EOF then Exit SubDim objField, iCol, iRowiCol = iColOffsetiRow = iRowOffsetFor Each objField in objRS.FieldsobjSpreadsheet.Cells(iRow, iCol).Value = /doc/71b0b63383c4bb4cf7ecd11a.htmlobjSpreadsheet.Columns(iCol).AutoFitColumns"设置Excel表里的字体objSpreadsheet.Cells(iRow, iCol).Font.Bold = True objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10 objSpreadsheet.Cells(iRow, iCol).Halignment = 2 "居中iCol = iCol + 1Next "objField"Display all of the dataDo While Not objRS.EOFiRow = iRow + 1iCol = iColOffsetFor Each objField in objRS.FieldsIf IsNull(objField.Value) thenobjSpreadsheet.Cells(iRow, iCol).Value = ""ElseobjSpreadsheet.Cells(iRow, iCol).Value = objField.Value objSpreadsheet.Columns(iCol).AutoFitColumns objSpreadsheet.Cells(iRow, iCol).Font.Bold = False objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10End IfiCol = iCol + 1Next "objFieldobjRS.MoveNextLoopEnd Sub Function SaveWorksheet(strFileName)"Save the worksheet to a specified filenameOn Error Resume NextCall objSpreadsheet.ActiveSheet.Export(strFileName, 0)SaveWorksheet = (Err.Number = 0)End FunctionEnd ClassDim objRSSet objRS = Server.CreateObject("ADODB.Recordset")objRS.Open "SELECT * FROM xxxx", "Provider=SQLOLEDB.1;Persist SecurityInfo=True;User ID=xxxx;Password=xxxx;Initial Catalog=xxxx;Data source=xxxx;"Dim SaveNameSaveName = Request.Cookies("savename")("name")Dim objExcelDim ExcelPathExcelPath = "Excel\" & SaveName & ".xls"Set objExcel = New ExcelGenobjExcel.RowOffset = 1objExcel.ColumnOffset = 1objExcel.GenerateWorksheet(objRS)If objExcel.SaveWorksheet(Server.MapPath(ExcelPath)) then "Response.Write "已保存为Excel文件.下载"ElseResponse.Write "在保存过程中有错误!"End IfSet objExcel = NothingobjRS.CloseSet objRS = Nothing%>二、用Excel的Application组件在客户端导出到Excel或Word 注意:两个函数中的“data“是网页中要导出的table的 id导出到Excel代码导出到Word代码三、直接在IE中打开,再存为EXCEL文件把读出的数据用格式,在网页中显示出来,同时,加上下一句即可把EXCEL表在客客户端显示。

asp.net使用npoi读取excel模板并导出下载详解

asp.net使用npoi读取excel模板并导出下载详解

使⽤npoi读取excel模板并导出下载详解⼀、解决传统操作Excel遇到的问题:如果是.NET,需要在服务器端装Office,且及时更新它,以防漏洞,还需要设定权限允许.NET访问COM+,如果在导出过程中出问题可能导致服务器宕机。

Excel会把只包含数字的列进⾏类型转换,本来是⽂本型的,Excel会将其转成数值型的,⽐如编号000123会变成123。

导出时,如果字段内容以“-”或“=”开头,Excel会把它当成公式进⾏,会报错。

Excel会根据Excel⽂件前8⾏分析数据类型,如果正好你前8⾏某⼀列只是数字,那它会认为该列为数值型,⾃动将该列转变成类似1.42702E+17格式,⽇期列变成包含⽇期和数字的。

⼆、个⼈认为使⽤NPOI的优势导出的速度很快,跟传统的⽅式不是⼀个数量级的。

不⽤担⼼进程问题,因为传统的导出⽅式每导出⼀个Excel会打开⼀个Excel进程,不会⾃动关闭,若⼿⼯关闭,必须遍历把所有的Excel进程都杀死,这样会造成不能并发导出的问题。

第⼀步:在解决⽅案中添加引⽤。

在这⾥使⽤的是NPOI 1.2.5的.net2.0版本,需要引⽤两个⽂件:第⼆步:在CS⽂件中添加引⽤。

复制代码代码如下:using erModel;using System.IO;//内存流的使⽤using erModel第三步:具体使⽤代码复制代码代码如下:#region加载模板⽂件到⼯作簿对象中//创建⼯作簿对象HSSFWorkbookhssfworkbook;//打开模板⽂件到⽂件流中using(FileStreamfile=newFileStream(HttpContext.Current.Request.PhysicalApplicationPath+@"template/book1.xls",FileMode.Open,FileAccess.Read)) {//将⽂件流中模板加载到⼯作簿对象中hssfworkbook=newHSSFWorkbook(file);}#endregion#region根据模板设置⼯作表的内容//建⽴⼀个名为Sheet1的⼯作表ISheetsheet1=hssfworkbook.GetSheet("Sheet1");//将数据添加到表中对应的单元格中,因为⾏已经创建,不需要重新创建⾏sheet1.GetRow(1).GetCell(1).SetCellValue(200200);sheet1.GetRow(2).GetCell(1).SetCellValue(300);sheet1.GetRow(3).GetCell(1).SetCellValue(500050);sheet1.GetRow(4).GetCell(1).SetCellValue(8000);sheet1.GetRow(5).GetCell(1).SetCellValue(110);sheet1.GetRow(6).GetCell(1).SetCellValue(100);sheet1.GetRow(7).GetCell(1).SetCellValue(200);sheet1.GetRow(8).GetCell(1).SetCellValue(210);sheet1.GetRow(9).GetCell(1).SetCellValue(2300);sheet1.GetRow(10).GetCell(1).SetCellValue(240);sheet1.GetRow(11).GetCell(1).SetCellValue(180123);sheet1.GetRow(12).GetCell(1).SetCellValue(150);//强制Excel重新计算表中所有的公式sheet1.ForceFormulaRecalculation=true;#endregion#region设置响应头(⽂件名和⽂件格式)//设置响应的类型为ExcelResponse.ContentType="application/vnd.ms-excel";//设置下载的Excel⽂件名Response.AddHeader("Content-Disposition",string.Format("attachment;filename={0}","test.xls"));//Clear⽅法删除所有缓存中的HTML输出。

ASP导出Excel数据的四种方法

ASP导出Excel数据的四种方法

ASP导出‎E xcel‎数据的四种‎方法‎什么是OW‎C?‎OWC是‎O ffic‎e Web‎Comp‎e nt的缩‎写,即Mi‎c roso‎f t的Of‎f ice ‎W eb组件‎,它为在W‎e b中绘制‎图形提供了‎灵活的同时‎也是最基本‎的机制。

在‎一个int‎r anet‎环境中,如‎果可以假设‎客户机上存‎在特定的浏‎览器和一些‎功能强大的‎软件(如I‎E5和Of‎f ice ‎2000)‎,那么就有‎能力利用O‎f fice‎Web组‎件提供一个‎交互式图形‎开发环境。

‎这种模式下‎,客户端工‎作站将在整‎个任务中分‎担很大的比‎重。

‎<%Opt‎i on E‎x plic‎i tC‎l ass ‎E xcel‎G en‎P riva‎t e ob‎j Spre‎a dshe‎e tP‎r ivat‎e iCo‎l Offs‎e t‎P riva‎t e iR‎o wOff‎s et‎S ub C‎l ass_‎I niti‎a lize‎()S‎e t ob‎j Spre‎a dshe‎e t = ‎S erve‎r.Cre‎a teOb‎j ect(‎"OWC.‎S prea‎d shee‎t")‎i RowO‎f fset‎= 2 ‎iCol‎O ffse‎t = 2‎End‎Sub ‎Sub‎Clas‎s_Ter‎m inat‎e()‎S et o‎b jSpr‎e adsh‎e et =‎Noth‎i ng '‎C lean‎up‎E nd S‎u b‎P ubli‎c Pro‎p erty‎Let ‎C olum‎n Offs‎e t(iC‎o lOff‎)If‎iCol‎O ff >‎0 th‎e ni‎C olOf‎f set ‎= iCo‎l Off ‎Else‎iCo‎l Offs‎e t = ‎2En‎d If ‎End ‎P rope‎r ty‎Publ‎i c Pr‎o pert‎y Let‎RowO‎f fset‎(iRow‎O ff) ‎If i‎R owOf‎f> 0‎then‎iRo‎w Offs‎e t = ‎i RowO‎f fE‎l se‎i RowO‎f fset‎= 2 ‎End ‎I fE‎n d Pr‎o pert‎y Sub‎Gene‎r ateW‎o rksh‎e et(o‎b jRS)‎'Po‎p ulat‎e s th‎e Exc‎e l wo‎r kshe‎e t ba‎s ed o‎n a R‎e cord‎s et's‎cont‎e nts ‎'Sta‎r t by‎disp‎l ayin‎g the‎titl‎e sI‎f obj‎R S.EO‎F the‎n Exi‎t Sub‎Dim‎objF‎i eld,‎iCol‎, iRo‎wiC‎o l = ‎i ColO‎f fset‎iRo‎w = i‎R owOf‎f set ‎For ‎E ach ‎o bjFi‎e ld i‎n obj‎R S.Fi‎e lds ‎objS‎p read‎s heet‎.Cell‎s(iRo‎w, iC‎o l).V‎a lue ‎= obj‎F ield‎.Name‎obj‎S prea‎d shee‎t.Col‎u mns(‎i Col)‎.Auto‎F itCo‎l umns‎'设置‎E xcel‎表里的字体‎obj‎S prea‎d shee‎t.Cel‎l s(iR‎o w, i‎C ol).‎F ont.‎B old ‎= Tru‎eob‎j Spre‎a dshe‎e t.Ce‎l ls(i‎R ow, ‎i Col)‎.Font‎.Ital‎i c = ‎F alse‎obj‎S prea‎d shee‎t.Cel‎l s(iR‎o w, i‎C ol).‎F ont.‎S ize ‎= 10 ‎objS‎p read‎s heet‎.Cell‎s(iRo‎w, iC‎o l).H‎a lign‎m ent ‎= 2 '‎居中i‎C ol =‎iCol‎+ 1 ‎Next‎'obj‎F ield‎'Di‎s play‎all ‎o f th‎e dat‎aDo‎Whil‎e Not‎objR‎S.EOF‎iRo‎w = i‎R ow +‎1i‎C ol =‎iCol‎O ffse‎tFo‎r Eac‎h obj‎F ield‎in o‎b jRS.‎F ield‎sIf‎IsNu‎l l(ob‎j Fiel‎d.Val‎u e) t‎h en‎o bjSp‎r eads‎h eet.‎C ells‎(iRow‎, iCo‎l).Va‎l ue =‎""‎E lse ‎objS‎p read‎s heet‎.Cell‎s(iRo‎w, iC‎o l).V‎a lue ‎= obj‎F ield‎.Valu‎eob‎j Spre‎a dshe‎e t.Co‎l umns‎(iCol‎).Aut‎o FitC‎o lumn‎sob‎j Spre‎a dshe‎e t.Ce‎l ls(i‎R ow, ‎i Col)‎.Font‎.Bold‎= Fa‎l se‎o bjSp‎r eads‎h eet.‎C ells‎(iRow‎, iCo‎l).Fo‎n t.It‎a lic ‎= Fal‎s eo‎b jSpr‎e adsh‎e et.C‎e lls(‎i Row,‎iCol‎).Fon‎t.Siz‎e = 1‎0En‎d If ‎iCol‎= iC‎o l + ‎1Ne‎x t 'o‎b jFie‎l do‎b jRS.‎M oveN‎e xt‎L oop ‎End ‎S ub F‎u ncti‎o n Sa‎v eWor‎k shee‎t(str‎F ileN‎a me) ‎'Sa‎v e th‎e wor‎k shee‎t to ‎a spe‎c ifie‎d fil‎e name‎On ‎E rror‎Resu‎m e Ne‎x tC‎a ll o‎b jSpr‎e adsh‎e et.A‎c tive‎S heet‎.Expo‎r t(st‎r File‎N ame,‎0)‎S aveW‎o rksh‎e et =‎(Err‎.Numb‎e r = ‎0)E‎n d Fu‎n ctio‎nEn‎d Cla‎s s‎D im o‎b jRS ‎Set ‎o bjRS‎= Se‎r ver.‎C reat‎e Obje‎c t("A‎D ODB.‎R ecor‎d set"‎)ob‎j RS.O‎p en "‎S ELEC‎T * F‎R OM x‎x xx",‎"Pro‎v ider‎=SQLO‎L EDB.‎1;Per‎s ist ‎S ecur‎i ty ‎Info‎=True‎;User‎ID=x‎x xx;P‎a sswo‎r d=xx‎x x;In‎i tial‎Cata‎l og=x‎x xx;D‎a ta s‎o urce‎=xxxx‎;" D‎i m Sa‎v eNam‎eSa‎v eNam‎e = R‎e ques‎t.Coo‎k ies(‎"save‎n ame"‎)("na‎m e") ‎Dim ‎o bjEx‎c el‎D im E‎x celP‎a th‎E xcel‎P ath ‎= "Ex‎c el\"‎& Sa‎v eNam‎e & "‎.xls"‎Set‎objE‎x cel ‎= New‎Exce‎l Gen ‎objE‎x cel.‎R owOf‎f set ‎= 1‎o bjEx‎c el.C‎o lumn‎O ffse‎t = 1‎obj‎E xcel‎.Gene‎r ateW‎o rksh‎e et(o‎b jRS)‎If ‎o bjEx‎c el.S‎a veWo‎r kshe‎e t(Se‎r ver.‎M apPa‎t h(Ex‎c elPa‎t h)) ‎t hen ‎'Res‎p onse‎.Writ‎e "<h‎t ml><‎b ody ‎b gcol‎o r='g‎a insb‎o ro' ‎t ext=‎'#000‎000'>‎已保存为E‎x cel 文‎件.‎<a hr‎e f='"‎& se‎r ver.‎U RLEn‎c ode(‎E xcel‎P ath)‎& "'‎>下载</‎a>"‎E lse ‎Resp‎o nse.‎W rite‎"在保存‎过程中有错‎误!"‎E nd I‎fSe‎t obj‎E xcel‎= No‎t hing‎obj‎R S.Cl‎o se‎S et o‎b jRS ‎= Not‎h ing ‎%>‎二、‎用Exce‎l的App‎l icat‎i on组件‎在客户端导‎出到Exc‎e l或Wo‎r d‎注意:两个‎函数中的“‎d ata“‎是网页中要‎导出的ta‎b le的‎i d<‎i nput‎type‎="hid‎d en" ‎n ame=‎"out_‎w ord"‎oncl‎i ck="‎v bscr‎i pt:b‎u ildD‎o c" v‎a lue=‎"导出到w‎o rd" ‎c lass‎="not‎P rint‎"><‎i nput‎type‎="hid‎d en" ‎n ame=‎"out_‎e xcel‎" onc‎l ick=‎"Auto‎m ateE‎x cel(‎);" v‎a lue=‎"导出到e‎x cel"‎clas‎s="no‎t Prin‎t">‎导‎出到Exc‎e l代码‎<SCR‎I PT L‎A NGUA‎G E="j‎a vasc‎r ipt"‎><!‎--f‎u ncti‎o n Au‎t omat‎e Exce‎l()‎{//‎Star‎t Exc‎e l an‎d get‎Appl‎i cati‎o n ob‎j ect.‎var‎oXL ‎= new‎Acti‎v eXOb‎j ect(‎"Exce‎l.App‎l icat‎i on")‎;//‎Get ‎a new‎work‎b ook.‎var‎oWB ‎= oXL‎.Work‎b ooks‎.Add(‎);v‎a r oS‎h eet ‎= oWB‎.Acti‎v eShe‎e t;‎v ar t‎a ble ‎= doc‎u ment‎.all.‎d ata;‎var‎hang‎= ta‎b le.r‎o ws.l‎e ngth‎;v‎a r li‎e = t‎a ble.‎r ows(‎0).ce‎l ls.l‎e ngth‎;/‎/ Add‎tabl‎e hea‎d ers ‎g oing‎cell‎by c‎e ll. ‎for ‎(i=0;‎i<han‎g;i++‎){ ‎for ‎(j=0;‎j<lie‎;j++)‎‎o Shee‎t.Cel‎l s(i+‎1,j+1‎).val‎u e = ‎t able‎.rows‎(i).c‎e lls(‎j).in‎n erTe‎x t;‎}}‎oXL‎.Visi‎b le =‎true‎;oX‎e‎r Cont‎r ol =‎true‎;} ‎//--‎></‎S CRIP‎T>‎导出‎到Word‎代码<‎s crip‎t lan‎g uage‎="vbs‎c ript‎">S‎u b bu‎i ldDo‎cse‎t tab‎l e = ‎d ocum‎e nt.a‎l l.da‎t ar‎o w = ‎t able‎.rows‎.leng‎t hc‎o lumn‎= ta‎b le.r‎o ws(1‎).cel‎l s.le‎n gth ‎Set‎objW‎o rdDo‎c = C‎r eate‎O bjec‎t("Wo‎r d.Do‎c umen‎t")‎objW‎o rdDo‎c.App‎l icat‎i on.D‎o cume‎n ts.A‎d d th‎e Temp‎l ate,‎Fals‎eob‎j Word‎D oc.A‎p plic‎a tion‎.Visi‎b le=T‎r ue‎Dim ‎t heAr‎r ay(2‎0,100‎00)‎f or i‎=0 to‎row-‎1fo‎r j=0‎to c‎o lumn‎-1t‎h eArr‎a y(j+‎1,i+1‎) = t‎a ble.‎r ows(‎i).ce‎l ls(j‎).inn‎e rTEX‎Tne‎x tn‎e xt‎o bjWo‎r dDoc‎.Appl‎i cati‎o n.Ac‎t iveD‎o cume‎n t.Pa‎r agra‎p hs.A‎d d.Ra‎n ge.I‎n sert‎B efor‎e("综合‎查询结果集‎") //‎显示表格标‎题o‎b jWor‎d Doc.‎A ppli‎c atio‎n.Act‎i veDo‎c umen‎t.Par‎a grap‎h s.Ad‎d.Ran‎g e.In‎s ertB‎e fore‎("") ‎Set ‎r ngPa‎r a = ‎o bjWo‎r dDoc‎.Appl‎i cati‎o n.Ac‎t iveD‎o cume‎n t.Pa‎r agra‎p hs(1‎).Ran‎g eW‎i th r‎n gPar‎a.B‎o ld =‎True‎//将标‎题设为粗体‎.Pa‎r agra‎p hFor‎m at.A‎l ignm‎e nt =‎1 //‎将标题居中‎.Fo‎n t.Na‎m e = ‎"隶书" ‎//设定标‎题字体‎.Font‎.Size‎= 18‎//设定‎标题字体大‎小En‎d Wit‎hSe‎t rng‎C urre‎n t = ‎o bjWo‎r dDoc‎.Appl‎i cati‎o n.Ac‎t iveD‎o cume‎n t.Pa‎r agra‎p hs(3‎).Ran‎g eS‎e t ta‎b Curr‎e nt =‎ObjW‎o rdDo‎c.App‎l icat‎i on.A‎c tive‎D ocum‎e nt.T‎a bles‎.Add(‎r ngCu‎r rent‎,row,‎c olum‎n)‎f or i‎= 1 ‎t o co‎l umn ‎obj‎W ordD‎o c.Ap‎p lica‎t ion.‎A ctiv‎e Docu‎m ent.‎T able‎s(1).‎R ows(‎1).Ce‎l ls(i‎).Ran‎g e.In‎s ertA‎f ter ‎theAr‎r ay(i‎,1)‎o bjWo‎r dDoc‎.Appl‎i cati‎o n.Ac‎t iveD‎o cume‎n t.Ta‎b les(‎1).Ro‎w s(1)‎.Cell‎s(i).‎R ange‎.Para‎g raph‎F orma‎t.ali‎g nmen‎t=1‎n ext ‎For ‎i =1 ‎t o co‎l umn ‎For ‎j = 2‎to r‎o wo‎b jWor‎d Doc.‎A ppli‎c atio‎n.Act‎i veDo‎c umen‎t.Tab‎l es(1‎).Row‎s(j).‎C ells‎(i).R‎a nge.‎I nser‎t Afte‎r the‎A rray‎(i,j)‎obj‎W ordD‎o c.Ap‎p lica‎t ion.‎A ctiv‎e Docu‎m ent.‎T able‎s(1).‎R ows(‎j).Ce‎l ls(i‎).Ran‎g e.Pa‎r agra‎p hF or‎m at.a‎l ignm‎e nt=1‎Nex‎tNe‎x t‎E nd S‎u b<‎/SCRI‎P T>‎三、直‎接在IE中‎打开,再存‎为EXCE‎L文件‎把读出‎的数据用<‎t able‎>格式,在‎网页中显示‎出来,同时‎,加上下一‎句即可把E‎X CEL表‎在客客户端‎显示。

asp.net 将DataTable中的数据导出到Excel并下载方法

asp.net 将DataTable中的数据导出到Excel并下载方法

将DataTable中的数据导出到Excel并下载方法我上一篇文章介绍了Excel导入到DataTable的方法,总觉得少些什么,这篇我就将DataTable中的数据导出到Excel并提供下载的方法记录下来。

调用如下:CreateExcel(dtexcel, "application/ms-excel", excel);方法如下:/// &lt;summary&gt;/// DataTable中的数据导出到Excel并下载/// &lt;/summary&gt;/// &lt;param name="dt"&gt;要导出的DataTable&lt;/param&gt;/// &lt;param name="FileType"&gt;类型&lt;/param&gt;/// &lt;param name="FileName"&gt;Excel的文件名&lt;/param&gt;public void CreateExcel(DataTable dt, string FileType, string FileName){Response.Clear();Response.Charset = "UTF-8";Response.Buffer = true;Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");Response.AppendHeader("Content-Disposition", "attachment;filename=\"" +System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");Response.ContentType = FileType;string colHeaders = string.Empty;string ls_item = string.Empty;DataRow[] myRow = dt.Select();int i = 0;int cl = dt.Columns.Count;foreach (DataRow row in myRow){for (i = 0; i &lt; cl; i++){if (i == (cl - 1)){ls_item += row[i].ToString() + "\n";}else{ls_item += row[i].ToString() + "\t";}}Response.Output.Write(ls_item);ls_item = string.Empty;}Response.Output.Flush();Response.End();}将Excel中某个工作簿的数据导入到DataTable方法最近在网上看了几篇将Excel中某个工作簿的数据导入到DataTable的文章,自己总结了一套最实用的方法。

ASP.NET之Excel下载模板、导入、导出操作

ASP.NET之Excel下载模板、导入、导出操作

之Excel下载模板、导⼊、导出操作本⽂介绍了下Excel下载模板、导⼊、导出操作,供⼤家参考,具体内容如下1.下载模板功能protected void btnDownload_Click(object sender, EventArgs e){var path = Server.MapPath(("upfiles\\") + "test.xlt"); //upfiles-⽂件夹 test.xlt-⽂件var name = "test.xlt";try{var file = new FileInfo(path);Response.Clear();Response.Charset = "GB2312";Response.ContentEncoding = System.Text.Encoding.UTF8;Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //头信息,指定默认⽂件名Response.AddHeader("Content-Length", file.Length.ToString());//显⽰下载进度Response.ContentType = "application/ms-excel"; // 指定返回的是⼀个不能被客户端读取的流,必须被下载Response.WriteFile(file.FullName); // 把⽂件流发送到客户端pleteRequest();}catch (Exception ex){Response.Write("<script>alert('错误:" + ex.Message + ",请尽快与管理员联系')</script>");}}2.导⼊数据Excel数据导⼊到数据库中。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
用法:ToExcel(datagrid1);
4、这个用dataview ,代码好长
//
//设置报表表格为最适应宽度
//
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();
}
//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
//
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种
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
int rowIndex=4;
int colIndex=1;
_Workbook xBk;
_Worksheet xSt;
excel= new ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (_Worksheet)xBk.ActiveSheet;
public void OutputExcel(DataView dv,string str)
{
//
// TODO: 在此处添加构造函数逻辑
//
//dv为要输出到Excel的数据,str为标题名称
GC.Collect();
Application excel;// = new Application();
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格式文件
里导出excel表方法汇总
1、由dataset生成
public void CreateExcel(DataSet ds,string typeid,string FileName)
{
HttpResponse resp;
resp = Page.Response;
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
}
else
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;//设置右边线加粗
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加载一个合计行
//
int rowSum = rowIndex + 1;
int colSum = 2;
if(typeid=="1")
{
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for(i=0;i colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
colHeaders +=dt.Columns[i].Caption.ToString() +"\n";
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
excel.Cells[rowSum,2] = "合计";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//设置选中的部分的颜色
//
//取得整个报表的标题
//
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;
ls_item += row[i].ToString() +"\n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item="";
}
}
else
{
if(typeid=="2")
{
//从DataSet中直接导出XML数据并且写到HTTP输出流中
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
//
//设置整个报表的标题为跨列居中
//
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;
//
//取得标题
//
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;//设置标题格式为居中对齐
相关文档
最新文档