ASP导出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生成Excel文件方法
ASP生成Excel文件方法ASP生成Excel文件方法方法一:导出到csv文件,存放在服务器端任一路径,然后给客户下载优点:1、可以进行身份认证后给客户下载,如果放到非web目录就没有对应的url,客户无法随时下载。
2、也是因为生成了文件,所以占用了服务器的空间,但是可以把文件名存放到数据库,再次给客户下载的时候不需要重复生成文件。
3、csv文件是文本文件,逗号隔开字段,回车隔开行,易于数据导入导出。
实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.T ables["table1"];string name="downloadurl"].ToString()+"yyyyMMdd")+new Random(".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数FileStream fs=newFileStream(name,FileMode.Create,FileAccess.Write);StreamWriter sw=new StreamWriter(fs,"gb2312"));sw.WriteLine("自动编号,姓名,年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename="+Server.UrlEncode(name));Response.ContentType="application/ms-excel";//指定返回的是一个不能被客户端读取的流,必须被下载Response.WriteFile(name);//把文件流发送到客户端Response.End();方法二:导出到csv文件,不存放到服务器,直接给浏览器输出文件流优点:1、随时生成,不需要占用资源2、可以结合身份认证3、同样利于数据交换实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.T ables["table1"];StringWriter sw=new StringWriter();sw.WriteLine("自动编号,姓名,年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename=test.csv");Response.ContentType="application/ms-excel";Response.ContentEncoding="GB2312");Response.Write(sw);Response.End();对方法一,二补充一点,如果你希望导出的是xls文件分隔符用\t 就可以了,不要用逗号代码修改如下:sw.WriteLine("自动编号\t姓名\t年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+"\t"+dr["vName"]+"\t"+dr["iAge"]);}另外,修改输出的文件扩展名为xls即可。
ASP.NET之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数据导入到数据库中。
用ASP生成Excel数据
用ASP生成Excel数据ASP最广泛的用途之一就是生成数据库驱动的Web 报告。
通常,这只是在浏览器内的一个HTML 表格中观看报告,但对于某些用户来说是不够的。
这些用户希望下载报告的数据,用他们自己的应用程序修改它们,这些应用程序包括电子表格软件(Microsoft Excel) 或本地数据库(Microsoft Access)。
我将用ASP 示范多种将数据输出到Microsoft Excel可读格式的技巧。
通过使用一个或多个这些技巧,你就可以在你的web 页面上放置一个“输出到Excel”的选项以满足那些用户。
原文出处:/articles/19991103.htm测试环境我使用以下环境创建并测试本文提供的样本:Windows NT 4/SP5 与 IIS 4Windows 95Internet Explorer 4.x 和 5Interdev 6Homesite 4.0Access 97Excel 97这可能是将一个html 表格变成 Microsoft Excel 格式的最快方法。
ContentType 属性通知浏览器数据要被格式化为何种格式,在这里我们要的格式是Microsoft Excel。
当浏览器看到这个属性的值是Excel 时,它就提示用户保存或打开这个文件。
如果用户选择打开文件,就启动了Excel并在其中观看数据。
为使其工作正确,必须在向Response对象写入任何内容之前设置ContentType 。
此语法的例子如下:Line 1: 〈 %@ LANGUAGE="VBSCRIPT" % 〉Line 2: Response.ContentType = "application/msexcel"Line 3: % 〉点击这里可以得到有关ASP的Response 对象的ContentType属性的更多信息。
当我试图用Internet Explorer 4.x.测试时发现了一个问题,在Microsoft文章 Q185978曾经提到过。
asp表格导出EXCEL的方法修改
asp中表格导出到EXCEL的方法一、第一种表格导出到Word代码、导出到EXCEL代码<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"><title>浏览器表格导出到Excel代码</title><input type="button" name="out_word" onclick="vbscript:buildDoc" value="导出到word" class="notPrint"><input type="button" name="out_word1" onclick="javascript:AutomateExcel() "value="导出到excel" class="notPrint"><table id="data" width="200" border="1"><tr><td>11</td><td>11</td></tr><tr><td>22</td><td>22</td></tr><tr><td>33</td><td>33</td></tr><tr><td>44 </td><td>44</td></tr></table><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, False objWordDoc.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).Range Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)for i = 1 to columnobjWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Inse rtAfter theArray(i,1)objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Para graphFormat.alignment=1nextFor i =1 to columnFor j = 2 to rowobjWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Inse rtAfter theArray(i,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Para graphFormat.alignment=1NextNextEnd Sub</SCRIPT>二、第二种如何在asp脚本里做个按钮可以将数据导出到excel表里-------------------------------------------------------------------------------方法一<input type="hidden" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint"><title>浏览器表格导出到Excel</title><input type="button" name="out_word1" onclick="java script:AutomateExcel() " value="导出到excel" class="notPrint"><table id="data" width="200" border="1"><tr><td>11</td><td>11</td></tr><tr><td>22</td><td>22</td></tr><tr><td>33</td><td>33</td></tr><tr><td>44 </td><td>44</td></tr></table><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>方法二<%@ LANGUAGE="VBSCRIPT" %><%option explicit%><%%><!--#include file="conn.asp"--><HTML><HEAD><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <TITLE>生成EXCEL文件</TITLE></HEAD><body><%dim rs,sql,filename,fs,myfile,x,linkSet fs = server.CreateObject("scripting.filesystemobject")filename = "f:\online.xls"if fs.FileExists(filename) thenfs.DeleteFile(filename)end ifset myfile = fs.CreateTextFile(filename,true)Set rs = Server.CreateObject("ADODB.Recordset")sql = "select * from table"rs.Open sql,connif 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 = nothingconn.closeset conn = nothingset myfile = nothingSet fs=Nothing%></BODY></HTML>//是从数据库里直接读出来再转到EXCEL中.要在页面上显示稍改下就成. 如何关闭excel进程dim excelappset excelapp=createobject("excel.application")............excelapp.quit'必备,建议上面加上on error resume next防止未知错误不能执行到此行set excelapp = nothing三、强人介绍的四种方法一、使用OWC 什么是OWC OWC是Office Web Compent的缩写,即Microsoft的Office Web 组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。
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的方法总结
导出数据到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表方法汇总
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";
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图片导出Excel的方法
将asp图片导出Excel的方法小编在网上找了很多要将asp图片导出Excel的方法,当时网上很多都是着实虚无,目前所知的方法有4种。
1.网上包括csdn大部分流行的方法,强制输出html格式为xls格式。
优点效率高,速度快。
缺点也很明显,毕竟不是真正的Excel格式,只是利用了office2000以后的版本可以直接打开html文件的特性强制生成的。
无法改变单元格格式等。
尤其是office2007,打开会提示您尝试打开的*xls"的格式与文件扩展名指定的格式不一致。
并且按保存时,会发现默认格式是txt。
这种方法不建议使用。
2.JavaScript格式,粗略的看了下。
有个致命的问题,要设置ie 安全属性。
一般用户会为了一个功能去繁琐的更高ie设置?而且也不是真正的csv格式,xls格式而已。
不考虑。
3.第三方控件,使用过MyXls这个控件,生成的真正的xls文件。
效率高,使用简单,不用考虑资源释放的问题。
可惜未发现导出图片的方法。
不过一般导出Excel的话,强烈推荐!4.使用微软的官方COM组件。
优点:功能强大。
缺点:效率低,需要手动关闭进程,释放资源,而且服务器端还需安装office。
暂时只发现这个可以导出图象到Excel。
方法如下:虽然服务器必须安装office,但并不需要安装完整版本的office,本人发现精简版也可以。
只不过设置麻烦一些而已。
先安装O2003PIA补丁。
下载地址百度。
网上一堆。
如果你安装完整版的office,可以跳过这部。
然后导入COM组件确定即可。
然后添加引用,如果安装的是完整版的,直接在引用的tab框中添加即可。
如果您是精简版的,下载个Microsoft.Office.Interop.Excel.dll。
然后放到网站根目录代码如下using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;//导入Com组件using Microsoft.Office.Core;//添加引用using ex=Microsoft.Office.Interop.Excel;using System.Reflection;public partial class _Default : System.Web.UI.Page {////// 导出图象到Excel/// 创建人:吴凯平/// 创建时间:2010年1月3日 12:46:38/////////protected void Page_Load(object sender, EventArgs e) {}////// 导出到Excel/////////protected void btnExcel_Click(object sender, EventArgs e){//声明一个默认值object missing = Missing.Value;//声明一个Excel应用程序对象ex.Application excelObj = new ex.ApplicationClass();//禁用Excel提示(否则第二次生成会提示是否覆盖等..)excelObj.DisplayAlerts = false;//不显示excel??excelObj.Visible = false;//创建workbooksex.Workbooks wbooks = excelObj.Workbooks;//使用Excel模板创建一个工作簿(模板必须先创建好放在网站可访问目录下)ex.Workbook wbook = wbooks.Open(Server.MapPath("模板路径"), missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,missing, missing);//新建一个excel工作表集合ex.Worksheets sheets = (ex.Worksheets)wbook.Worksheets;//新建一个工作表ex._Worksheet sheet = (ex._Worksheet)sheets.get_Item(1);//声明一个pictures对象,用来存放sheet的图片ex.Pictures pics = (ex.Pictures)sheet.Pictures(missing);//设置要插入的图片路径pics.Insert(Server.MapPath("图片路径"),MsoTriState.msoFalse, MsoTriState.msoCTrue);//插入图片}}////// 输出Excel/////////protected void ImageButton1_Click(object sender, ImageClickEventArgs e){if (chltStat.Visible == false){ClientScript.RegisterStartupScript(GetType(), "", "alert('没有数据请生成数据再导入!');", true);return;}object missing = Missing.Value;//定义一个Excel应用程序ex.ApplicationClass excelObj = new ex.ApplicationClass();excelObj.DisplayAlerts = false;excelObj.Visible = false;ex.Workbooks wbooks = excelObj.Workbooks;ex.Workbook wbook = wbooks.Open(Server.MapPath("../动态经营统计数据.xls"), missing, missing, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing);ex.Sheets sheets = (ex.Sheets)wbook.Worksheets;ex._Worksheet sheet = (ex._Worksheet)sheets.get_Item(1);ex.Range exRange = (ex.Range)sheet.get_Range("B2", missing);exRange.Select();//声明一个pictures对象,用来存放柱状图ex.Pictures pics = (ex.Pictures)sheet.Pictures(missing);//插入图片pics.Insert(Server.MapPath("Chartlet_chltStat_区企业年度信息统计表_Bar.Jpg"), missing);sheet.Shapes.AddPicture(Server.MapPath("Chartlet_chltStat 2_区企业年度信息统计表_Line.Jpg"),Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoCTrue,50, 400, 570, 368);//504 326wbook.SaveAs(Server.MapPath("../xls/动态经营统计数据.xls"), missing, missing, missing, missing, missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoCh ange, missing, missing, missing, missing,missing);wbook.Close(false, missing, missing);excelObj.Quit();ClientScript.RegisterStartupScript(GetType(), "", "window.location.href='../xls/动态经营统计数据.xls';", true);//必须关闭释放所引用的COM对象,关闭Excel进程,否则会占用服务器资源ReleaseObj(sheets);ReleaseObj(wbook);ReleaseObj(wbooks);ReleaseObj(excelObj);System.GC.Collect();System.GC.WaitForPendingFinalizers();//BindGv();string filePath = Server.MapPath("../xls/动态经营统计数据.xls");Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("动态经营统计数据", System.Text.Encoding.UTF8) + ".xls");Response.ContentType = "Application/excel";Response.WriteFile(filePath);Response.End();}。
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页⾯导出成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我们在做项目的时候经常要将数据库的数据导出到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数据的四种方法一、使用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导出为Word或Excel的最简单方法
Asp代码EXC EL <% Res ponse.Cont entTy pe ="appli catio n/vnd.ms-e xcel"Re spons e.Add Heade r "Co ntent-Disp ositi on","atta chmen t; fi lenam e=表格.xls"%>WORD<% Respo nse.C onten tType ="ap plica tion/vnd.m s-wor d" Respo nse.A ddHea der "Conte nt-Di sposi tion", "at tachm ent;filen ame=文档.doc" %>导出为W ORD时,若文档中含有表格,需要打打印,则要在导出的页面中加入下面的样式。
C ss代码<st yle t ype="text/css"><!-- tab le{ bor der-c ollap se:co llaps e;bor der:n one;m so-bo rder-alt:s olidwindo wtext .5pt; mso-y fti-t blloo k:480;mso-paddi ng-al t:0cm 5.4p t 0cm 5.4p t;mso-bord er-in sideh: .5ptsolid wind owtex t;mso-bord er-in sidev:.5pt soli d win dowte xt;bo rder-left:solidwind owtex t 1.0pt;bo rder-top:s olidwindo wtext 1.0p t; } td{bo rder-top:n one;b order-left: none;borde r-bot tom:s olidwindo wtext 1.0p t;bor der-r ight:solid wind owtex t 1.0pt; mso-bord er-to p-alt:soli d win dowte xt .5pt;ms o-bor der-l eft-a lt:so lid w indow text.5pt;m so-bo rder-alt:s olidwindo wtext .5pt;padd ing:0cm 5.4pt 0cm 5.4pt;}--> </sty le> <st yle t ype="text/css"><!--tabl e{bo rder-colla pse:c ollap se;bo rder:none;mso-b order-alt:solid wind owtex t .5p t;ms o-yft i-tbl look:480;m so-pa dding-alt:0cm 5.4pt0cm 5.4pt;mso-b order-insi deh:.5ptsolid wind owtex t;mso-bord er-in sidev:.5pt soli d win dowte xt;bo rder-left:solidwind owtex t 1.0pt;bo rder-top:s olidwindo wtext 1.0p t;}td{b order-top:none;borde r-lef t:no ne;bo rder-botto m:sol id wi ndowt ext 1.0pt;borde r-rig ht:so lid w indow text1.0pt;mso-bord er-to p-alt:soli d win dowte xt .5pt;ms o-bor der-l eft-a lt:so lid w indow text.5pt; mso-borde r-alt:soli d win dowte xt .5pt;pa dding:0cm5.4pt 0cm5.4pt;}--></style>系统项目中的一个导出为EXCEL文件的实例代码如下:Asp代码<!--#inclu de fi le="h bwlCo nfig.asp"--> <%R espon se.Co ntent Type="app licat ion/v nd.ms-exce l" Re spons e.Add Heade r "Co ntent-Disp ositi on","atta chmen t; fi lenam e=che ngji.xls"%> <!DOC TYPEhtmlPUBLI C "-//W3C//DTDXHTML 1.0Trans ition al//E N""h ttp://www.w3.or g/TR/xhtml1/DTD/xhtm l1-tr ansit ional.dtd"> <html xmln s="ht tp://www.w3.org/1999/xhtm l"> <he ad> <me ta ht tp-eq uiv="Conte nt-Ty pe" c onten t="te xt/ht ml; c harse t=utf-8" /> <titl e>成绩</titl e> <sty le ty pe="t ext/c ss">.t ableW g {bo rder:1px s olid#9bbd e6;}.t ableW g tr{text-align:cent er;}.t ableW g td{ bord er-bo ttom:1px d otted #9bb de6;borde r-rig ht:1p x dot ted #9bbde6;} </s tyle></head> <body> <%sql=sess ion("cheng jisql") resp onse.Write hbwl.dbSe lect(sql,0,1,"",0,"",0,"t ableW g")%></body> </htm l> <%se t hbw l=not hing%>。
asp导出excel并打印报表
asp导出excel并打印报表1.前言报表打印通常是管理信息系统中的一个重要模块,而Excel凭借它功能强大、应用灵活、通用性强等的优势在报表打印中获得了广泛的应用。
最初的管理信息系统基本上是采用客户机/服务器(C/S)模式开发的,但随着WWW的广泛应用,目前的管理信息系统已经逐渐开始从C/S模式向浏览器/服务器(B/S)模式转变。
B/S模式具有传统C/S模式所不及的很多特点,如更加开放、与软硬件无关、应用扩充和系统维护升级方便等等,目前已成为企业网上首选的计算模式,原先在C/S下的很多软件都开始移植到B/S模式下。
由于B/S模式的特殊性,在C/S下相对较易实现的Excel报表打印功能在B/S下却成为一个难点。
本文根据在实际的项目中总结的经验,以ASP为例,给出了一个较好的通用方法。
2. 功能实现为了说明问题,这里举一个例子。
系统平台是Windows 2000+SQL Server 2000+IIS5.0+ASP 3,报表采用的是Excel,要求按照给定的报表格式生成图书销售统计的报表,并能够打印。
2.1 Excel报表模板的制作首先根据给定的报表格式,制作一个Excel模板(就是要打印的报表的表格),当然其中需要从数据库中动态统计生成的数据留着空白。
这个报表先在Excel中画好,然后保存为模板,存放在起来,这里为\test\book1.xlt。
2.2 Excel报表的生成与打印这里采用了Excel的Application组件,该组件在安装Excel时安装到系统中。
我们的操作也都是针对该组件。
(1) 建立Excel.Application对象set objExcel=CreateObject("Excel.Application")(2) 打开Excel模板objExcel.Workbooks.Open(server.mappath("\test")&"\book1.xlt") '打开Excel模板objExcel.Sheets(1).select '选中工作页set sheetActive=objExcel.ActiveWorkbook.ActiveSheet(3) Excel的常规添加操作例如sheetActive.range("g4").value=date() …这里添加的是时间,当然也可以是你指定的任何数据(4) Excel中添加数据库中的纪录这里假设已有一个数据集adoRset,存放由Sql操作生成的统计数据。
ASP导出Excel数据的四种方法
ASP导出E xcel数据的四种方法什么是OWC?OWC是O ffice WebCompe nt的缩写,即Mic rosof t的Off ice W eb组件,它为在We b中绘制图形提供了灵活的同时也是最基本的机制。
在一个intr anet环境中,如果可以假设客户机上存在特定的浏览器和一些功能强大的软件(如IE5和Off ice 2000),那么就有能力利用Of ficeWeb组件提供一个交互式图形开发环境。
这种模式下,客户端工作站将在整个任务中分担很大的比重。
<%Opti on Ex plici tCl ass E xcelG enP rivat e obj Sprea dshee tPr ivate iCol Offse tP rivat e iRo wOffs etS ub Cl ass_I nitia lize()Se t obj Sprea dshee t = S erver.Crea teObj ect("OWC.S pread sheet")i RowOf fset= 2 iColO ffset = 2EndSub SubClass_Term inate()S et ob jSpre adshe et =Nothi ng 'C leanupE nd Su bP ublic Prop ertyLet C olumn Offse t(iCo lOff)IfiColO ff >0 the niC olOff set = iCol Off ElseiCol Offse t = 2End If End P roper tyPubli c Pro perty LetRowOf fset(iRowO ff) If iR owOff> 0theniRow Offse t = i RowOf fEl sei RowOf fset= 2 End I fEn d Pro perty SubGener ateWo rkshe et(ob jRS)'Pop ulate s the Exce l wor kshee t bas ed on a Re cords et'sconte nts 'Star t bydispl aying thetitle sIf objR S.EOF then Exit SubDimobjFi eld,iCol, iRowiCo l = i ColOf fsetiRow = iR owOff set For E ach o bjFie ld in objR S.Fie lds objSp reads heet.Cells(iRow, iCo l).Va lue = objF ield.NameobjS pread sheet.Colu mns(i Col).AutoF itCol umns'设置E xcel表里的字体objS pread sheet.Cell s(iRo w, iC ol).F ont.B old = Trueobj Sprea dshee t.Cel ls(iR ow, i Col).Font.Itali c = F alseobjS pread sheet.Cell s(iRo w, iC ol).F ont.S ize = 10 objSp reads heet.Cells(iRow, iCo l).Ha lignm ent = 2 '居中iC ol =iCol+ 1 Next'objF ield'Dis playall o f the dataDoWhile NotobjRS.EOFiRow = iR ow +1iC ol =iColO ffsetFor Each objF ieldin ob jRS.F ieldsIfIsNul l(obj Field.Valu e) th eno bjSpr eadsh eet.C ells(iRow, iCol).Val ue =""E lse objSp reads heet.Cells(iRow, iCo l).Va lue = objF ield.Valueobj Sprea dshee t.Col umns(iCol).Auto FitCo lumnsobj Sprea dshee t.Cel ls(iR ow, i Col).Font.Bold= Fal seo bjSpr eadsh eet.C ells(iRow, iCol).Fon t.Ita lic = Fals eob jSpre adshe et.Ce lls(i Row,iCol).Font.Size = 10End If iCol= iCo l + 1Nex t 'ob jFiel dob jRS.M oveNe xtL oop End S ub Fu nctio n Sav eWork sheet(strF ileNa me) 'Sav e the work sheet to a spec ified file nameOn E rrorResum e Nex tCa ll ob jSpre adshe et.Ac tiveS heet.Expor t(str FileN ame,0)S aveWo rkshe et =(Err.Numbe r = 0)En d Fun ctionEnd Clas sD im ob jRS Set o bjRS= Ser ver.C reate Objec t("AD ODB.R ecord set")obj RS.Op en "S ELECT * FR OM xx xx","Prov ider=SQLOL EDB.1;Pers ist S ecuri ty Info=True;UserID=xx xx;Pa sswor d=xxx x;Ini tialCatal og=xx xx;Da ta so urce=xxxx;" Di m Sav eNameSav eName = Re quest.Cook ies("saven ame")("nam e") Dim o bjExc elD im Ex celPa thE xcelP ath = "Exc el\"& Sav eName & ".xls"SetobjEx cel = NewExcel Gen objEx cel.R owOff set = 1o bjExc el.Co lumnO ffset = 1objE xcel.Gener ateWo rkshe et(ob jRS)If o bjExc el.Sa veWor kshee t(Ser ver.M apPat h(Exc elPat h)) t hen 'Resp onse.Write "<ht ml><b ody b gcolo r='ga insbo ro' t ext='#000000'>已保存为Ex cel 文件.<a hre f='"& ser ver.U RLEnc ode(E xcelP ath)& "'>下载</a>"E lse Respo nse.W rite"在保存过程中有错误!"E nd IfSet objE xcel= Not hingobjR S.Clo seS et ob jRS = Noth ing %>二、用Excel的Appl icati on组件在客户端导出到Exce l或Wor d注意:两个函数中的“d ata“是网页中要导出的tab le的i d<i nputtype="hidd en" n ame="out_w ord"oncli ck="v bscri pt:bu ildDo c" va lue="导出到wo rd" c lass="notP rint"><i nputtype="hidd en" n ame="out_e xcel" oncl ick="Autom ateEx cel();" va lue="导出到ex cel"class="not Print">导出到Exce l代码<SCRI PT LA NGUAG E="ja vascr ipt"><!--fu nctio n Aut omate Excel(){//Start Exce l and getAppli catio n obj ect.varoXL = newActiv eXObj ect("Excel.Appl icati on");//Get a newworkb ook.varoWB = oXL.Workb ooks.Add();va r oSh eet = oWB.Activ eShee t;v ar ta ble = docu ment.all.d ata;varhang= tab le.ro ws.le ngth;va r lie = ta ble.r ows(0).cel ls.le ngth;// Addtable head ers g oingcellby ce ll. for (i=0;i<hang;i++){ for (j=0;j<lie;j++)o Sheet.Cell s(i+1,j+1).valu e = t able.rows(i).ce lls(j).inn erTex t;}}oXL.Visib le =true;oXer Contr ol =true;} //--></S CRIPT>导出到Word代码<s cript lang uage="vbsc ript">Su b bui ldDocset tabl e = d ocume nt.al l.dat aro w = t able.rows.lengt hco lumn= tab le.ro ws(1).cell s.len gth SetobjWo rdDoc = Cr eateO bject("Wor d.Doc ument")objWo rdDoc.Appl icati on.Do cumen ts.Ad d the Templ ate,Falseobj WordD oc.Ap plica tion.Visib le=Tr ueDim t heArr ay(20,10000)f or i=0 torow-1for j=0to co lumn-1th eArra y(j+1,i+1) = ta ble.r ows(i).cel ls(j).inne rTEXTnex tne xto bjWor dDoc.Appli catio n.Act iveDo cumen t.Par agrap hs.Ad d.Ran ge.In sertB efore("综合查询结果集") //显示表格标题ob jWord Doc.A pplic ation.Acti veDoc ument.Para graph s.Add.Rang e.Ins ertBe fore("") Set r ngPar a = o bjWor dDoc.Appli catio n.Act iveDo cumen t.Par agrap hs(1).Rang eWi th rn gPara.Bo ld =True//将标题设为粗体.Par agrap hForm at.Al ignme nt =1 //将标题居中.Fon t.Nam e = "隶书" //设定标题字体.Font.Size= 18//设定标题字体大小End WithSet rngC urren t = o bjWor dDoc.Appli catio n.Act iveDo cumen t.Par agrap hs(3).Rang eSe t tab Curre nt =ObjWo rdDoc.Appl icati on.Ac tiveD ocume nt.Ta bles.Add(r ngCur rent,row,c olumn)f or i= 1 t o col umn objW ordDo c.App licat ion.A ctive Docum ent.T ables(1).R ows(1).Cel ls(i).Rang e.Ins ertAf ter theArr ay(i,1)o bjWor dDoc.Appli catio n.Act iveDo cumen t.Tab les(1).Row s(1).Cells(i).R ange.Parag raphF ormat.alig nment=1n ext For i =1 t o col umn For j = 2to ro wob jWord Doc.A pplic ation.Acti veDoc ument.Tabl es(1).Rows(j).C ells(i).Ra nge.I nsert After theA rray(i,j)objW ordDo c.App licat ion.A ctive Docum ent.T ables(1).R ows(j).Cel ls(i).Rang e.Par agrap hF orm at.al ignme nt=1NextNex tE nd Su b</SCRIP T>三、直接在IE中打开,再存为EXCEL文件把读出的数据用<t able>格式,在网页中显示出来,同时,加上下一句即可把EX CEL表在客客户端显示。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
objSpreadsheet.Cells(iRow, iCol).Font.Italic = False
objSpreadsheet.Cells(iRow, iCol).Font.Size = 10
objSpreadsheet.Cells(iRow, iCol).Halignment = 2 "居中
iCol = iCol + 1
Next "objField
"Display all of the data
Do While Not objRS.EOF
iRow = iRow + 1
iCol = iColOffset
For Each objField in objRS.Fields
= "隶书" //设定标题字体
.Font.Size = 18 //设定标题字体大小
End With
Set rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).Range
Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)
objWordDoc.Application.Visible=True
Dim theArray(20,10000)
for i=0 to row-1
for j=0 to column-1
theArray(j+1,i+1) = table.rows(i).cells(j).innerTEXT
for i = 1 to column
objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.InsertAfter theArray(i,1)
导出到Excel代码
<SCRIPT LANGUAGE="javascript">
<!--
function AutomateExcel()
{
// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application");
If IsNull(objField.Value) then
objSpreadsheet.Cells(iRow, iCol).Value = ""
Else
objSpreadsheet.Cells(iRow, iCol).Value = objField.Value
objSpreadsheet.Columns(iCol).AutoFitColumns
End If
iCol = iCol + 1
Next "objField
objRS.MoveNext
Loop
End Sub Function SaveWorksheet(strFileName)
"Save the worksheet to a specified filename
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "SELECT * FROM xxxx", "Provider=SQLOLEDB.1;Persist Security
Info=True;User ID=xxxx;Password=xxxx;Initial Catalog=xxxx;Data source=xxxx;"
// Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var table = document.all.data;
var hang = table.rows.length;
"Response.Write "<html><body bgcolor="gainsboro" text="#000000">已保存为Excel文件.
<a href="" & server.URLEncode(ExcelPath) & "">下载</a>"
Else
Response.Write "在保存过程中有错误!"
<%
Option Explicit
Class ExcelGen
Private objSpreadsheet
Private iColOffset
Private ffset
Sub Class_Initialize()
Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet")
Dim SaveName
SaveName = Request.Cookies("savename")("name")
Dim objExcel
Dim ExcelPath
ExcelPath = "Excel\" & SaveName & ".xls"
Set objExcel = New ExcelGen
objSpreadsheet.Cells(iRow, iCol).Value =
objSpreadsheet.Columns(iCol).AutoFitColumns
"设置Excel表里的字体
objSpreadsheet.Cells(iRow, iCol).Font.Bold = True
}
}
oXL.Visible = true;
erControl = true;
}
//-->
</SCRIPT>
导出到Word代码
<script language="vbscript">
Sub buildDoc
set table = document.all.data
next
next
objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("综合查询结果集") //显示表格标题
objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("")
On Error Resume Next
Call objSpreadsheet.ActiveSheet.Export(strFileName, 0)
SaveWorksheet = (Err.Number = 0)
End Function
End Class
Dim objRS
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;
row = table.rows.length
column = table.rows(1).cells.length
Set objWordDoc = CreateObject("Word.Document")
objWordDoc.Application.Documents.Add theTemplate, False
iRowOffset = 2
iColOffset = 2
End Sub
Sub Class_Terminate()
Set objSpreadsheet = Nothing "Clean up
End Sub
Public Property Let ColumnOffset(iColOff)
If iColOff > 0 then
iColOffset = iColOff
Else
iColOffset = 2
End If
End Property
Public Property Let RowOffset(iRowOff)
If iRowOff > 0 then
ASP导出Excel数据的四种方法2007/08/02 02:25 P.M.一、使用OWC
什么是OWC?
OWC是Office Web Compent的缩写,即Microsoft的Office Web组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。在一个intranet环境中,如果可以假设客户机上存在特定的浏览器和一些功能强大的软件(如IE5和Office 2000),那么就有能力利用Office Web组件提供一个交互式图形开发环境。这种模式下,客户端工作站将在整个任务中分担很大的比重。