ASP生成Excel文件方法
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表格导出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表方法汇总
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.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.net生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)
生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)页面导航:→ → → → 正文内容生成Excel文件并下载 生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)这里采用的是在服务端先生成Excel文件,然后利用文件地址下载的方法。
生成Excel文件的方法,见:.Net创建Excel文件(插入数据、修改格式、生成图表)的方法先试用Response.WriteFile的方法:复制代码代码如下:FileInfo fi = new FileInfo(excelFile);//excelFile为文件在服务器上的地址HttpResponse contextResponse = HttpContext.Current.Response; contextResponse.Clear();contextResponse.Buffer = true;contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现contextResponse.AppendHeader("Content-Disposition",String.Format("attachment;filename={0}", excelName)); //定义输出文件和文件名contextResponse.AppendHeader("Content-Length", fi.Length.ToString()); contextResponse.ContentEncoding = Encoding.Default; contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
contextResponse.WriteFile(fi.FullName);contextResponse.Flush();contextResponse.End();其中第一行的excelFile为Excel文件在服务器上的地址,比如:“C:\Website\Excel\xx.xlsx”。
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%>。
SAP生成Excel
TYPE-POOLS: ole2 .1.T-CODE: SMW0上传Excel模板1.在程序中调用变量声明:DATA: l_excel_obj TYPE ole2_object, l_workbook_obj TYPE ole2_object,l_sheet_obj TYPE ole2_object.DATA: l_fname LIKE rlgrap-filename,l_filename TYPE string,l_icount TYPE i,l_irow TYPE i.1.2取得模板文件和路径PERFORM temp_excel_get CHANGING l_fname.FORM temp_excel_get CHANGING fname.DATA: l_objdata LIKE wwwdatatab,l_destination LIKE rlgrap-filename,l_rc LIKE sy-subrc,l_errtxt TYPE string.SELECT SINGLE relid objidFROM wwwdataINTO CORRESPONDING FIELDS OF l_objdataWHERE srtf2 = 0AND relid = 'MI'AND objid = 'ZP001MMR019'. "此处为EXCEL模板名称* 检查表wwwdata中是否存在所指定的模板文件IF sy-subrc NE0ORl_objdata-objid = space."如果不存在,则给出错误提示CONCATENATE'保函交接模板文件''不存在'INTO l_errtxt.MESSAGE l_errtxt TYPE'E'.ENDIF.l_destination = 'C:\保函交接单.XLS'.* 如果存在,调用DOWNLOAD_WEB_OBJECT 函数下载模板到路径下CALL FUNCTION'DOWNLOAD_WEB_OBJECT'EXPORTINGkey = l_objdatadestination = l_destinationIMPORTINGrc = l_rc.IF l_rc NE0.CONCATENATE'保函交接单模板文件:' l_destination '下载失败'INTO l_errtxt.MESSAGE l_errtxt TYPE'E'.ENDIF.fname = l_destination.ENDFORM. " TEMP_EXCEL_GET1.3以模板生成文件PERFORM open_excel_file USING l_excel_objl_workbook_objl_sheet_objl_fname'1' .FORM open_excel_file USING l_excell_workbookl_sheetl_filenamel_visible.CREATE OBJECT l_excel 'Excel.Application'.IF sy-subrc NE0.MESSAGE e796(f9) WITH'不能创建Excel对象'.ENDIF.CALL METHOD OF l_excel 'Workbooks' = l_workbook.CALL METHOD OF l_workbook 'Open' = l_workbook EXPORTING #1 = l_filename.IF sy-subrc NE0.MESSAGE e796(f9) WITH'打开文件错误'.ENDIF.SET PROPERTY OF l_excel 'Visible' = l_visible.CALL METHOD OF l_workbook 'Sheets' = l_sheet EXPORTING #1 = 1.ENDFORM. " OPEN_EXCEL_FILE1.4插入表格行数计算内表的行数DESCRIBE TABLE gt_out LINES l_icount.l_icount = l_icount - 1.复制空行数PERFORM excel_row_insert USING l_sheet_obj'4'l_icount.FORM excel_row_insert USING l_sheetl_rowl_count.DATA l_range TYPE ole2_object.DO l_count TIMES.CALL METHOD OF l_sheet 'Rows' = l_rangeEXPORTING #1 = l_row.CALL METHOD OF l_range 'Copy'.CALL METHOD OF l_sheet 'Rows' = l_rangeEXPORTING #1 = l_row.CALL METHOD OF l_range 'Insert'.CALL METHOD OF l_range 'ClearContents'. "是否需要清空Cell ENDDO.ENDFORM. " EXCEL_ROW_INSERT1.5写值到表格中l_irow = 3.LOOP AT gt_out.l_irow = l_irow + 1.PERFORM write_item USING l_excel_objl_irow.ENDLOOP.FORM write_item USING l_excel_objl_row.DATA: l_count TYPE i.l_count = l_row - 3.PERFORM excel_cell_write USING l_excel_objl_row'A'l_count.PERFORM excel_cell_write USING l_excel_objl_row'B'gt_out-bhno.ENDFORM. " WRITE_ITEMFORM excel_cell_write USING l_excell_rowl_coll_value.DATA: l_cell TYPE ole2_object.CALL METHOD OF l_excel 'Cells' = l_cellEXPORTING #1 = l_row#2 = l_col.SET PROPERTY OF l_cell 'Value' = l_value.ENDFORM. " EXCEL_CELL_WRITE2.拓展,多个Sheet3.1 在Excel中录制宏宏名称:SheetCopy宏代码:Sub SheetCopy()'' SheetCopy MacroSheets("Sheet1").SelectSheets("Sheet1").Copy After:=Sheets(1)End Sub2.2创建Sheet个数DATA:l_excel_obj TYPE ole2_object,l_workbook_obj TYPE ole2_object,l_sheet_obj TYPE ole2_object.DATA:l_sheet_name TYPE string,l_sheetno TYPE i,l_sheetcnt TYPE i.PERFORM create_sheets USING l_excel_objl_sheetcnt.FORM create_sheets USING l_excel_objl_hcount.DO l_hcount TIMES.CALL METHOD OF l_excel_obj 'RUN'EXPORTING#1 = 'SheetCopy'.ENDDO.ENDFORM. " CREATE_SHEETS2.3修改Sheet名称PERFORM change_sheetname USING l_workbook_objl_sheet_objl_sheet_namel_sheetno.FORM change_sheetname USING l_workbook_obj l_sheet_objl_sheet_namel_sheetno.CALL METHOD OF l_workbook_obj 'Sheets' = l_sheet_objEXPORTING#1 = ls_sheetno.SET PROPERTY OF l_sheet_obj 'Name' = l_sheet_name.CALL METHOD OF l_sheet_obj 'Activate' .ENDFORM. " CHANGE_SHEETNAME。
asp中把数据导出为excel的2种方法
asp中把数据导出为excel的2种⽅法我们在做项⽬的时候经常要将数据库的数据导出到excel中,很多asp⽤户并不知道怎么写。
这⾥明凯总结了两种⽅法来导出excel,希望能帮到⼤家。
⽅法⼀:⽤excel组件< %set rs=server.createobject("adodb.recordset")sql="select * from mkusers"rs.open sql,objconn,1,1Set ExcelApp =CreateObject("Excel.Application")ExcelApp.Application.Visible = TrueSet ExcelBook = ExcelApp.Workbooks.AddExcelBook.WorkSheets(1).cells(1,1).value ="⽤户表"ExcelBook.WorkSheets(1).cells(2,1).value = "⽤户编号"ExcelBook.WorkSheets(1).cells(2,2).value = "登陆名"ExcelBook.WorkSheets(1).cells(2,3).value = "真实姓名"ExcelBook.WorkSheets(1).cells(2,4).value = "密码"cnt =3do while not rs.eofExcelBook.WorkSheets(1).cells(cnt,1).value = rs("provinceid")ExcelBook.WorkSheets(1).cells(cnt,2).value = rs("province")ExcelBook.WorkSheets(1).cells(cnt,3).value = rs("flag")ExcelBook.WorkSheets(1).cells(cnt,4).value = rs("id")rs.movenextcnt = cint(cnt) + 1loopExcelbook.SaveAs "d:\yourfile.xls" '这个是数据导出完毕以后在D盘存成⽂件ExcelApp.Application.Quit '导出以后退出ExcelSet ExcelApp = Nothing '注销Excel对象%>< %set rs=server.createobject("adodb.recordset")sql="select * from mkusers"rs.open sql,objconn,1,1Set ExcelApp =CreateObject("Excel.Application")ExcelApp.Application.Visible = TrueSet ExcelBook = ExcelApp.Workbooks.AddExcelBook.WorkSheets(1).cells(1,1).value ="⽤户表"ExcelBook.WorkSheets(1).cells(2,1).value = "⽤户编号"ExcelBook.WorkSheets(1).cells(2,2).value = "登陆名"ExcelBook.WorkSheets(1).cells(2,3).value = "真实姓名"ExcelBook.WorkSheets(1).cells(2,4).value = "密码"cnt =3do while not rs.eofExcelBook.WorkSheets(1).cells(cnt,1).value = rs("provinceid")ExcelBook.WorkSheets(1).cells(cnt,2).value = rs("province")ExcelBook.WorkSheets(1).cells(cnt,3).value = rs("flag")ExcelBook.WorkSheets(1).cells(cnt,4).value = rs("id")rs.movenextcnt = cint(cnt) + 1loopExcelbook.SaveAs "d:\yourfile.xls" '这个是数据导出完毕以后在D盘存成⽂件ExcelApp.Application.Quit '导出以后退出ExcelSet ExcelApp = Nothing '注销Excel对象%>⽅法⼆:使⽤⽂件组件< %dim s,sql,filename,fs,myfile,xSet fs = server.CreateObject("scripting.filesystemobject")'--假设你想让⽣成的EXCEL⽂件做如下的存放filename = Server.MapPath("order.xls")'--如果原来的EXCEL⽂件存在的话删除它if fs.FileExists(filename) thenfs.DeleteFile(filename)end if'--创建EXCEL⽂件set myfile = fs.CreateTextFile(filename,true)StartTime = Request("StartTime")EndTime = Request("EndTime")StartEndTime = "AddTime between #"& StartTime &" 00:00:00# and #"& EndTime &" 23:59:59#"strSql = "select * from mksuers "Set rstData =conn.execute(strSql)if not rstData.EOF and not rstData.BOF thendim trLine,responsestrstrLine=""For each x in rstData.fieldsstrLine = strLine & & chr(9)Next'--将表的列名先写⼊EXCELmyfile.writeline strLineDo while Not rstData.EOFstrLine=""for each x in rstData.FieldsstrLine = strLine & x.value & chr(9)nextmyfile.writeline strLinerstData.MoveNextloopend ifResponse.Write "⽣成EXCEL⽂件成功,点击<a href="/" rel="external nofollow" order.xls"" target=""_blank"">下载!"rstData.Closeset rstData = nothingConn.CloseSet Conn = nothing%>可以看出,第⼀种⽅法是直接导出的是excel⽂件,⽽第⼆张⽅法是到处的是⽂本⽂件,只不过后缀名改成了xls。
asp操作Excel的方法
大中小
楼主
asp 操作Excel的方法 之前java用jxl ,.net 就不用说了。 现在用easp做个web 站点,类似商城的,其中有个需求是要求对以选中的商品进行exce l 导出操作。还有一个需求是用户不想逐条后台添加商品,想要直接导入excel 文件,然 后程序按字段读取后更新。 一、 这个站点最初的版本很有意思,excel 的导出实际上是csv格式的文件,这个比较好办, 生成文本逗号分隔即可。缺点是没有格式。 而批量上传则是在服务器端做存储过程,用vb写了个客户端工具。用户需要先将数据录 入mdb 数据库,然后通过客户端工具“上传”。 二、 对于导出excel 的功能。第一次改动是将csv文件改为html 格式,并更改后缀为xls 。 这样改完之后可以用excel 打开,模板也可以任意调整。但office2003 以上版本打开该文 件时会弹出安全提示:要打开的文件实际类型与后缀不符。虽然不影响最终阅读,但很 不人性化。 三、 既然是微软的excel ,那么就继续尝试,安装了微软的owc 组件。通过owc 组件进行exce l 文档生成,没想到的是,微软的owc 生成的,竟然是标准的xml格式,和第二次改动一 样,只是改了个后缀。这样一来,效果和上面是一样的,也会产生安全提示。 由于效果不好,这个代码也就不贴了。网上有很多,有需要的自己搜索。 四、 接下来,查阅了大量资料之后使用了一个方法,就是通过web 直接调用excel 的com组件 进行文件读写操作。本质上讲,这个和用office 软件打开excel 文件是一样的,因此生成 的效果很好。但是由于是直接调用com组件,因此需要在服务器上有相应权限。使用这 个方法,在操作excel 的时候,服务器的进程中会出现excel.exe 的进程,而且在发生某
ASP.NETCore中使用EPPlus导入出Excel文件的完整步骤
Core中使⽤EPPlus导⼊出Excel⽂件的完整步骤前⾔这篇⽂章说明了如何使⽤EPPlus在 Core中导⼊和导出.xls/.xlsx⽂件(Excel)。
在考虑使⽤.NET处理excel时,我们总是寻找第三⽅库或组件。
使⽤Open Office Xml格式(xlsx)读取和写⼊Excel 2007/2010⽂件的最流⾏的.net库之⼀是。
这个库现在已经⽀持.NET Core许久了。
这适⽤于Windows,Linux和Mac。
因此,让我们创建⼀个新的 Core WEB API应⽤程序并安装EPPlus.Core。
要安装EPPlus.Core,请在程序包管理器控制台中运⾏以下命令:PM->Install-Package EPPlus.Core或者您可以通过UI界⾯来安装它.⼀切就绪,现在创建⼀个控制器,命名为: ImportExportController ,添加后,让我们编写导出⽅法。
为了⽅便演⽰,我在wwwroot⽂件夹中创建了⼀个excel⽂件,所以我们就需要去获取我们的项⽬的绝对路径。
public class ImportExportController : ControllerBase{private readonly IHostingEnvironment _hostingEnvironment;public ImportExportController(IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}}ExcelPackage 在 OfficeOpenXml 命名空间中可⽤的类将⽤于读写xlsx。
定义名为“Export”的新Web api操作⽅法,该⽅法返回⽣成的xlsx⽂件的URL。
所以这是将数据导出到xlsx的完整代码。
其中您需要 using OfficeOpenXml;[HttpGet]public string Export(){string sWebRootFolder = _hostingEnvironment.WebRootPath;string sFileName = @"demo.xlsx";string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);FileInfo file = new FileInfo(bine(sWebRootFolder, sFileName));if (file.Exists){file.Delete();file = new FileInfo(bine(sWebRootFolder, sFileName));}using (ExcelPackage package = new ExcelPackage(file)){// add a new worksheet to the empty workbookExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");//First add the headersworksheet.Cells[1, 1].Value = "ID";worksheet.Cells[1, 2].Value = "Name";worksheet.Cells[1, 3].Value = "Gender";worksheet.Cells[1, 4].Value = "Salary (in $)";//Add valuesworksheet.Cells["A2"].Value = 1000;worksheet.Cells["B2"].Value = "Jon";worksheet.Cells["C2"].Value = "M";worksheet.Cells["D2"].Value = 5000;worksheet.Cells["A3"].Value = 1001;worksheet.Cells["B3"].Value = "Graham";worksheet.Cells["C3"].Value = "M";worksheet.Cells["D3"].Value = 10000;worksheet.Cells["A4"].Value = 1002;worksheet.Cells["B4"].Value = "Jenny";worksheet.Cells["C4"].Value = "F";worksheet.Cells["D4"].Value = 5000;package.Save(); //Save the workbook.}return URL;}就这样。
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表在客客户端显示。
使用Aspose.Cells组件生成Excel文件实例
使⽤Aspose.Cells组件⽣成Excel⽂件实例⽣成带表头的Excel⽂件,格式如下显⽰。
当然更复杂的⼀些也可以通过合并单元格的⽅法 public void Merge(int firstRow, int firstColumn, int totalRows, int totalColumns)来实现。
1. ⾸先,需要添加对"Aspose.Cells.dll"的引⽤。
2. 实现代码如下:复制代码代码如下://新建⼯作簿Workbook workbook = new Workbook(); //⼯作簿Worksheet sheet = workbook.Worksheets[0]; //⼯作表Cells cells = sheet.Cells;//单元格Style style = workbook.Styles[workbook.Styles.Add()];//新增样式#region 表头//标题style.HorizontalAlignment = TextAlignmentType.Center;//⽂字居中 = "宋体";//⽂字字体style.Font.Size = 18;//⽂字⼤⼩style.Font.IsBold = true;//粗体cells.Merge(0, 0, 1, 12); //合并单元格cells[0, 0].PutValue("标准化⼯作意见建议汇总表"); //填写内容cells[0, 0].SetStyle(style); //给单元格关联样式cells.SetRowHeight(0, 28); //设置⾏⾼//发布时间style.HorizontalAlignment = TextAlignmentType.Left;style.Font.Size = 11;style.Font.IsBold = false;cells.Merge(1, 0, 1, 7);cells[1, 0].PutValue(String.Format("发布起⽌时间:{0}⾄{1}",DateTime.Now.AddDays(-1).ToString("yyyy年MM⽉dd ⽇"),DateTime.Now.ToString("yyyy年MM⽉dd⽇")));cells[1, 0].SetStyle(style);cells.SetRowHeight(1, 20);//统计时间style.HorizontalAlignment = TextAlignmentType.Right;style.Font.Size = 11;style.Font.IsBold = false;cells.Merge(1, 7, 1, 5);cells[1, 7].PutValue(String.Format("统计时间:{0}", DateTime.Now.ToString("yyyy年MM⽉dd⽇")));cells[1, 7].SetStyle(style);cells.SetRowHeight(1, 20);#endregion#region 表格#region 表格标题⾏//序号style.HorizontalAlignment = TextAlignmentType.Center;cells[2, 0].PutValue("序号");cells[2, 0].SetStyle(style);cells.SetRowHeight(2, 20);cells.SetColumnWidthPixel(0, 38);//建议时间cells[2, 1].PutValue("建议时间");cells[2, 1].SetStyle(style);cells.SetColumnWidthPixel(1, 77);//建议部门cells[2, 2].PutValue("建议部门");cells[2, 2].SetStyle(style);cells.SetColumnWidthPixel(2, 107);//建议⼈cells[2, 3].PutValue("建议⼈");cells[2, 3].SetStyle(style);cells.SetColumnWidthPixel(3, 69);//类别cells[2, 4].PutValue("类别");cells[2, 4].SetStyle(style);cells.SetColumnWidthPixel(4, 71);//业务种类cells[2, 5].PutValue("业务种类");cells[2, 5].SetStyle(style);cells.SetColumnWidthPixel(5, 71);//标准名称cells[2, 6].PutValue("标准名称");cells[2, 6].SetStyle(style);cells.SetColumnWidthPixel(6, 114);//标准章、条编号cells[2, 7].PutValue("标准章、条编号");cells[2, 7].SetStyle(style);cells.SetColumnWidthPixel(7, 104);//意见建议cells[2, 8].PutValue("意见建议");cells[2, 8].SetStyle(style);cells.SetColumnWidthPixel(8, 255);//处理部门cells[2, 9].PutValue("处理部门");cells[2, 9].SetStyle(style);cells.SetColumnWidthPixel(9, 72);//处理进度cells[2, 10].PutValue("处理进度");cells[2, 10].SetStyle(style);cells.SetColumnWidthPixel(10, 72);//备注cells[2, 11].PutValue("备注");cells[2, 11].SetStyle(style);cells.SetColumnWidthPixel(11, 255);#endregion#endregionSystem.IO.MemoryStream ms = workbook.SaveToStream();//⽣成数据流 byte[] bt = ms.ToArray();workbook.Save(@"E:\test.xls");//保存到硬盘}复制代码代码如下://下载System.IO.MemoryStream ms = workbook.SaveToStream();//⽣成数据流byte[] bt = ms.ToArray();string fileName = "标准化⼯作意见建议汇总表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//客户端保存的⽂件名//以字符流的形式下载⽂件Response.ContentType = "application/vnd.ms-excel";//通知浏览器下载⽂件⽽不是打开Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));Response.BinaryWrite(bt);Response.Flush();Response.End();。
asp生成excel源代码
<!--#include file="../conn.asp"--><%dim s,sql,filename,fs,myfile,xSet fs = server.CreateObject("scripting.filesystemobject")'--假设你想让生成的EXCEL文件做如下的存放filename = Server.MapPath("班班通使用记录登记表.xls")'--如果原来的EXCEL文件存在的话删除它if fs.FileExists(filename) thenfs.DeleteFile(filename)end if'--创建EXCEL文件set myfile = fs.CreateTextFile(filename,true)Set rs = Server.CreateObject("ADODB.Recordset")'--从数据库中把你想放到EXCEL中的数据查出来sql = "select teacher_Name,teacher_use_time,teacher_use_class,teacher_use_snumber,teacher_use_jc,teacher_ use_ctitle,teacher_use_couse from teacher_use_table order by teacher_use_ID desc"rs.Open sql,connStartTime = Request("StartTime")EndTime = Request("EndTime")StartEndTime = "AddTime between #"& StartTime &" 00:00:00# and #"& EndTime &" 23:59:59#"strSql = "select teacher_Name,teacher_use_time,teacher_use_class,teacher_use_snumber,teacher_use_jc,teacher_ use_ctitle,teacher_use_couse from teacher_use_table"Set rstData =conn.execute(strSql)if not rstData.EOF and not rstData.BOF thendim trLine,responsestrstrLine=""strLine = strLine & "上课教师" & chr(9)strLine = strLine & "上课时间" & chr(9)strLine = strLine & "使用班级" & chr(9)strLine = strLine & "学生人数" & chr(9)strLine = strLine & "使用节次" & chr(9)strLine = strLine & "上课学科" & chr(9)strLine = strLine & "课程名称" & chr(9)'--将表的列名先写入EXCELmyfile.writeline strLineDo while Not rstData.EOFstrLine=""for each x in rstData.FieldsstrLine = strLine & x.value & chr(9)nextmyfile.writeline strLinerstData.MoveNextloopend ifResponse.Write "<br> 生成EXCEL文件成功,点击<a href=""班班通使用记录登记表.xls"" target=""_blank"">下载</a>!"rstData.Closeset rstData = nothingConn.CloseSet Conn = nothing%>。
ASP生成excel表格
ASP生成excel表格!<%dim excelstringdim excelstrdim excelstr2dim headexcelstring = ""head = "Sn" & "," & "Reason" & "," & "Empid" & "," & "Empname" & "," & "Ext" & "," & "Depname" excel="creat"If excel<>"" ThenSet rs2 = Server.CreateObject ("ADODB.Recordset")sql2 = "Select * from value_table "rs2.open sql2,conn,1,3do while not rs2.eofexcelstr =" " & rs2(0) & """,""" & rs2(1) & """,""" & rs2(2) & """,""" & rs2(3) & """,""" & rs2(4) & """,""" & rs2(5) & """"excelstr2 = excelstr2 & Chr(13) & excelstrrs2.movenextloopexcelstring = head &Chr(13)& excelstr2'response.Write(excelstring)'rs2.closeSet rs2=Nothingset fs = CreateObject("scripting.FileSystemObject")set exc = fs.OpenTextFile(server.MapPath("excel.csv"),2,True)exc.write(excelstring)if fs.FileExists(Server.MapPath("excel.csv")) thenResponse.Write("<a href=excel.csv>报表已经生成,点击查看</a>")'Response.write(excelstring)elseResponse.Write("生成报表失败!")end ifEnd if%>调试通过!----------------------------------------------------------------------------------------------这可能是将一个html 表格变成Microsoft Excel 格式的最快方法。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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.Tables["table1"];string name="downloadurl"].ToString()+"yyyyMMdd")+newRandom(".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.Tables["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即可。
方法三:从datagrid导出html代码,生成excel文件,给客户端下载优点:1、有固定的格式,样子好看(datagrid的样子)局限性:1、不适合数据交换,里面有html代码,比较乱,没有固定格式2、datagrid不能有分页、排序等,否则出错实现方法:Response.Clear();Response.Buffer=false;Response.Charset="GB2312";Response.AppendHeader("Content-Disposition","attachment;filename=test.xls");Response.ContentEncoding="GB2312");Response.ContentType="application/ms-excel";this.EnableViewState=false;oStringWriter=new ;oHtmlTextWriter=new ;;Response.Write(oStringWriter.ToString());Response.End();在这里说明一点:有的网友反映代码出现"没有dr["id"]"之类的错误,这个代码是按照我的数据结构来写的,到时候相关的字段要换成你自己的才是。
还有就是如果文件名需要中文的话,这么修改Response.AddHeader("Content-Disposition","attachment;filename="+"中文",".xls");目录一、环境配置二、ASP对Excel的基本操作三、ASP操作Excel生成数据表四、ASP操作Excel生成Chart图五、服务器端Excel文件浏览、下载、删除方案六、附录正文一、环境配置服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:1.Win9x+PWS+Office2.Win2000 Professional+PWS+Office3.Win2000 Server+IIS+Office目前笔者测试成功的环境是后二者。
Office的版本没有特殊要求,考虑到客户机配置的不确定性和下兼容特性,建议服务器端Office版本不要太高,以防止客户机下载后无法正确显示。
服务器端环境配置还有两个偶然的发现是:1.笔者开发机器上原来装有金山的WPS2002,结果Excel对象创建始终出现问题,卸载WPS2002后,错误消失。
2.笔者开发ASP代码喜欢用FrontPage,结果发现如果FrontPage打开(服务器端),对象创建出现不稳定现象,时而成功时而不成功。
扩展考察后发现,Office系列的软件如果在服务器端运行,则Excel对象的创建很难成功。
服务器端还必须要设置的一点是COM组件的操作权限。
在命令行键入"DCOMCNFG",则进入COM组件配置界面,选择Microsoft Excel后点击属性按钮,将三个单选项一律选择自定义,编辑中将Everyone加入所有权限。
保存完毕后重新启动服务器。
客户端的环境配置没发现什么特别讲究的地方,只要装有Office和IE 即可,版本通用的好象都可以。
二、ASP对Excel的基本操作1、建立Excel对象set objExcelApp=CreateObject("Excel.Application")objExcelApp.DisplayAlerts=false不显示警告2、新建Excel文件set objExcelBook=objExcelApp.ActiveWorkBook set objExcelSheets=objExcelBook.Worksheets setobjExcelSheet=objExcelBook.Sheets(1)3、读取已有Excel文件strAddr=Server.MapPath(".")"\Templet\Table.xls")set objExcelBook=objExcelApp.ActiveWorkBook set objExcelSheets=objExcelBook.Worksheets setobjExcelSheet=objExcelBook.Sheets(1)4、另存Excel文件objExcelBook.SaveAs strAddr&"\Temp\Table.xls"5、保存Excel文件objExcelBook.Save(笔者测试时保存成功,页面报错。
)6、退出Excel操作objExcelApp.Quit一定要退出set objExcelApp=Nothing三、ASP操作Excel生成数据表1、在一个范围内插入数据objExcelSheet.Range("B3:k3").Value=Array("67","87","5","9","7","45","45","54","54","10")2、在一个单元格内插入数据objExcelSheet.Cells(3,1).Value="Internet Explorer"3、选中一个范围4、单元格左边画粗线条5、单元格右边画粗线条6、单元格上边画粗线条7、单元格下边画粗线条8、单元格设定背景色9、合并单元格10、插入行11、插入列四、ASP操作Excel生成Chart图1、创建Chart图2、设定Chart图种类注:二维折线图,4;二维饼图,5;二维柱形图,51 3、设定Chart图标题"A test Chart"4、通过表格数据设定图形objExcelSheet.Range("A1:k5"),1 5、直接设定图形数据(推荐)"=""333""""={1,4,5,6,2}"6、绑定Chart图17、显示数据表8、显示图例五、服务器端Excel文件浏览、下载、删除方案浏览的解决方法很多,"Location.href=","Navigate","Response.Redirect"都可以实现,建议用客户端的方法,原因是给服务器更多的时间生成Excel文件。