asp写入excel
ASP.NETCore导入导出Excelxlsx文件实例

Core导⼊导出Excelxlsx⽂件实例 Core 使⽤EPPlus.Core导⼊导出Excel xlsx ⽂件,EPPlus.Core⽀持Excel 2007/2010 xlsx⽂件导⼊导出,可以运⾏在Windows, Linux和Mac。
EPPlus.Core 是基于EPPlus 更改⽽来,在Linux 下需要安装libgdiplus 。
下⾯在 Core 中导⼊导出Excel xlsx ⽂件。
新建项⽬新建⼀个 Core Web Application 项⽬ASPNETCoreExcel,选择Web 应⽤程序不进⾏⾝份验证。
然后添加EPPlus.Core 引⽤。
使⽤NuGet 命令⾏:Install-Package EPPlus.Core也可以使⽤NuGet包管理器安装。
导出xlsx⽂件新建⼀个XlsxController ,添加Export 操作。
public class XlsxController : Controller{private IHostingEnvironment _hostingEnvironment;public XlsxController(IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}public IActionResult Index(){return View();}public IActionResult Export(){string sWebRootFolder = _hostingEnvironment.WebRootPath;string sFileName = $"{Guid.NewGuid()}.xlsx";FileInfo file = new FileInfo(bine(sWebRootFolder, sFileName));using (ExcelPackage package = new ExcelPackage(file)){// 添加worksheetExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");//添加头worksheet.Cells[1, 1].Value = "ID";worksheet.Cells[1, 2].Value = "Name";worksheet.Cells[1, 3].Value = "Url";//添加值worksheet.Cells["A2"].Value = 1000;worksheet.Cells["B2"].Value = "LineZero";worksheet.Cells["C2"].Value = "/linezero/";worksheet.Cells["A3"].Value = 1001;worksheet.Cells["B3"].Value = "LineZero GitHub";worksheet.Cells["C3"].Value = "https:///linezero";worksheet.Cells["C3"].Style.Font.Bold = true;package.Save();}return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");}}通过依赖注⼊获取HostingEnvironment,对应可以获取程序的相关⽬录及属性。
ASP对Excel的所有操作

A: 同一用户生成的Excel文件用同一个文件名,文件名可用用户ID号或SessionID号等可确信不重复字符串组成。这样新文件生成时自动覆盖上一文件。
B: 在Global.asa文件中设置Session_onEnd事件激发时,删除这个用户的Excel暂存文件。
C: 在Global.asa文件中设置Application_onStart事件激发时,删除暂存目录下的所有文件。
6、 绑定Chart图
objExcelApp.ActiveChart.Location 1
7、 显示数据表
objExcelApp.ActiveChart.HasDataTable = True
8、 显示图例
objExcelApp.ActiveChart.DataTable.ShowLegendKey = True
目录
一、 环境配置
二、 ASP对Excel的基本操作
三、 ASP操作Excel生成数据表
四、 ASP操作E件浏览、下载、删除方案
六、 附录
正文
一、 环境配置
服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:
1.Win9x+PWS+Office
2、 新建Excel文件
objExcelApp.WorkBooks.add
set objExcelBook = objExcelApp.ActiveWorkBook
set objExcelSheets = objExcelBook.Worksheets
set objExcelSheet = objExcelBook.Sheets(1)
使用Aspose插件对Excel操作

使⽤Aspose插件对Excel操作使⽤使⽤Aspose插件对Excel⽂档进⾏导⼊导出操作使⽤前请先下载Aspose插件引⽤Excel导⼊:前台使⽤file标签获取,submit⽅式提交。
<form id="form1" enctype="multipart/form-data" method="post"><table class="table-condensed"><tr><td class="text-right">导⼊表格:</td><td class="text-left"><input type="file" name="file1" class="btn btn-default btn-lg"/></td></tr><tr><td class="text-left"><input type="submit" id="btnImport" name="btnImport" value="导⼊" class="btn btn-default"/></td></tr></table></form>后台接收:HttpPostedFileBase fileBase = Request.Files["file1"];//这⾥获取名称与前台标签name保持⼀致if (fileBase != null){string filename = Path.GetFileName(fileBase.FileName);string extension = Path.GetExtension(filename);string path = "/Upload/Test/" + DateTime.Now.ToString("yyyyMMdd") + "/";Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(path)));string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff");string fullFileName = path + newFilename + extension;fileBase.SaveAs(Request.MapPath(fullFileName)); try{ Stopwatch sw = new Stopwatch();//记录导⼊操作⽤时多长sw.Start();//这⾥可放⼊BLL⽅法处理string result = new ProductBLL().ImportExcel(Request.MapPath(path), newFilename, extension);//BLL⽅法 ProductBLLpublic string ImportExcel(string path, string filename, string extension){Workbook workbook = new Workbook(path + filename + extension);Worksheet worksheet = workbook.Worksheets[0];Cells cells = worksheet.Cells;for (int i = 1; i < cells.Rows.Count; i++){try{string brand = cells[i, 0].StringValue.Trim();//获取列值string years = cells[i, 1].StringValue.Trim();}catch (Exception e){continue;}}return "OK";} sw.Stop();long runTime = sw.ElapsedMilliseconds / 1000; //获取到操作⽤时多少秒 } catch (Exception e){Log.Write("导⼊", "导⼊错误", "错误信息:" + e.Message);}}Excel导出:string path = "/Upload/Test/" + DateTime.Now.ToString("yyyyMMdd") + "/";Directory.CreateDirectory(Path.GetDirectoryName(Server.MapPath(path)));string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";string fullFileName = Server.MapPath(path + newFilename);public void ExportInfo(List<Test> list, string fullFileName){Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[0];cellSheet.PageSetup.LeftMargin = 0.3;//左边距cellSheet.PageSetup.RightMargin = 0.3;//右边距cellSheet.PageSetup.TopMargin = 1;//上边距cellSheet.PageSetup.BottomMargin = 0.5;//下边距cellSheet.PageSetup.FooterMargin = 0.5;//页脚cellSheet.PageSetup.HeaderMargin = 0.5;//页眉cellSheet.PageSetup.Orientation = ndscape;cellSheet.PageSetup.CenterHorizontally = true;//⽔平居中cellSheet.PageSetup.CenterVertically = true;cellSheet.Cells[0, 0].PutValue("货号");cellSheet.Cells[0, 1].PutValue("颜⾊");cellSheet.Cells[0, 2].PutValue("尺码");int i = 1;foreach (var item in list){cellSheet.Cells[i, 0].PutValue(item.productno);cellSheet.Cells[i, 1].PutValue(item.size);cellSheet.Cells[i, 2].PutValue(item.color);i++;}cellSheet.AutoFitColumns();fullFileName = Path.GetFullPath(fullFileName);workbook.Save(fullFileName);}return File(fullFileName, "application/ms-excel", UserName + "_Test单" + newFilename);// ⽅法Action⾥直接返回File⽂件下载。
将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中怎么把页面中的数据导出到EXCEL

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

用ASP访问excel中的数据1、建立一个链接文件名为conn。
<%db="D:\标件.xlsx" '用的是数据实际路径哈’set conn =server.CreateObject("adodb.connection")connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & db + "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1';"conn.open connstr ’打开excel%>2、查询excel表格中的内容。
<%sqlstr="select * from [标件2010年$] order by 序列desc" ‘查询语句set rs =server.CreateObject("adodb.recordset")rs.open sqlstr,conn,0,1rs.movefirstdo while not rs.eof %><tr><td width='50' height='20'><%response.write(rs("序列"))%></td><td width='70' height='20'><%response.write(rs("标准"))%></td><td width='100' height='20'><%response.write(rs("名称"))%></td><td width='60' height='20'><%response.write(rs("材质"))%></td><td width='120' height='20'><%response.write(rs("规格型号"))%></td><td width="60" height="20"><%response.write(rs("单位"))%></td><td width="120" height="20"><%response.write(rs("入库数量"))%></td><td width="50" height="20"><%response.write(rs("入库时间"))%></td><td width="80" height="20"><%response.write(rs("出库数量"))%></td><td width="80" height="20"><%response.write(rs("出库时间"))%></td><td width="80" height="20"><%response.write(rs("领用人"))%></td><td width="70" height="20"><%response.write(rs("合同号"))%></td><td width="80" height="20"><%response.write(rs("库存数量"))%></td><td width="60" height="20"><%response.write(rs("备注"))%></td></tr><%rs.movenextloopresponse.Write"</table>"conn.close%>。
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应用程序中实现Excel报表处理

2 编程 实现 E cl xe 报表处 理
21 xe 数据导入数据库的实现 . E cl 读 出 E cl xe 文档 中数据 的主要操 作步 骤 为 : ) ( 1
获 得 E cl 档 的路 径 和文件 名 ,打 开 E cl xe 文 xe 文 档 ;2 打开工 作表 , ( ) 建立 记录 集. 这里 需要 特别说 明的是 , 要打 开 的工作 表名 一定 要写 成 “ 名¥t 【 表 】 t
据库 和 南 Mi oo ces数据 库 中 的数据 生 成 c sf A cs r t
E cl 档 ,ቤተ መጻሕፍቲ ባይዱ出编程 实 现方法 , x e文 提 并给 出源 程序 .
1 AS P程序访 问 E cl xe 文档 的基本原理
A P是 一种 服务 器端 脚本 执行 环境 ,使 用它 S
可 以创建 和运 行 动态 、 互 的 We 应 用程 序 . P 交 b AS
的形 式 ;() 3 读各 单元 格 的值 . 其实 现 过程 如下 .
<hm l t > <he d a > <m e ht - q v CO e — p ”c tn =”e / t lc a s t m tp e ui=” ntm Ty e one t txt m ; h re = - h - g b231 ” 2 >
可 以结合 HT 、 本命 令 和 AccX组 件 , 同 ML 脚 te i 共 创建 动态 的We 页和基 于 we 服务 器 的功能 强大 b b
的应 用程 序. S A P可 以通 过 A O AcvX D t O . D ( te a b i a
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
<%@ LANGUAGE="VBSCRIPT" %><%option explicit%><HTML><HEAD><meta content="text/html; charset=gb2312" http-equiv="Content-Type"> <TITLE>生成EXCEL文件</TITLE></HEAD><body><a href="dbtoexcel.asp?act=make">生成EXCEL文件</a><hr size=1 align=left width=300px><%if Request("act") = "" thenResponse.Write "生成EXCEL文件"elsedim conn,strconnstrconn="driver={SQL Server};server=xxx;uid=sa;pwd=;database=DB_Test" set conn=server.CreateObject("adodb.connection")conn.Open strconndim rs,sql,filename,fs,myfile,xSet fs = server.CreateObject("scripting.filesystemobject")'--假设你想让生成的EXCEL文件做如下的存放filename = Server.MapPath("online.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 * from Tb_Execl order by sort desc"rs.Open sql,connif rs.EOF and rs.BOF thenResponse.Write "库里暂时没有数据!"elsedim strLine,responsestrstrLine=""For each x in rs.fieldsstrLine= strLine & & chr(9) Next'--将表的列名先写入EXCELmyfile.writeline strLineDo while Not rs.EOFstrLine=""for each x in rs.FieldsstrLine= strLine & x.value & chr(9) next'--将表的数据写入EXCELmyfile.writeline strLiners.MoveNextloopend ifrs.Closeset rs = nothingconn.closeset conn = nothingset myfile = nothingSet fs=Nothingend if%></BODY></HTML><!--#include file="conn.asp"--><span style="color: #6633FF"><%dim s,sql,filename,fs,myfile,x,rsSet fs = server.CreateObject("scripting.filesystemobject")'--假设你想让生成的EXCEL文件做如下的存放filename = Server.MapPath("users.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 * from product order by 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 * from product order by id desc"Set rstData =conn.execute(strSql)if not rstData.EOF and not rstData.BOF thendim trLine,responsestrstrLine=""strline = strline & "设备名称" & chr(9) & "设备编码" & chr(9) & "设备型号" & chr(9) & "设备简介" & chr(9) & "配发时间" & chr(9) & "库存情况" & chr(9) & "单价(元)" & chr(9) & "存放地" & chr(9)'--将表的列名先写入EXCELmyfile.writeline strLineDo while Not rstdata.EOFstrLine=""strLine = strLine & rs("name")& chr(9) & rs("type")& chr(9) & rs("mark") & c hr(9) & rs("introduce")&chr(9) & rs("adddate")& chr(9) & rs("amount")& chr(9) & rs("p rice1")& chr(9) & rs("bzz1")& chr(9)myfile.writeline strLinerstData.MoveNextloopend ifResponse.Write "生成EXCEL文件成功,<a href=""users.xls"" target=""_blank"">点击右键目标另存为下载</a>!"rstData.Closeset rstData = nothingConn.CloseSet Conn = nothing%></span>常要把各种各样的查询结果输出到EXCEL中,所以做了下面这段小程序,用于把一个SQL 的SELECT查询出的结果输出为EXCEL格式文件,这个程序你只要设好用于取得一个记录集的SQL的SELECT查询语句和一个文件名,程序就能输出EXCEL格式文件了,这个程序一共由三个文件构成,第一个文件的文件名为:toexcel.asp是主文件,内容如下:<%'前面是和来链接到数据库,请自行书写相关语句,此处略过sql=session("toexcelsql") '这里是要输出EXCEL的查询语句,如 "SESECT * FORM CAI WHERE 性别='女'"filename="excel.xls" ' 要输出的EXCEL文件的文件名, 你只要改以上两句就行了,其它的都不要改.'你只要修改以上两变量就行了.其它的我都做好了.call toexcel(FILENAME,sql)set conn=nothingfunction ReadT ext(FileName) '这是一个用于读出文件的函数set adf=server.CreateObject("Adodb.Stream")with adf.Type=2.LineSeparator=10.Open.LoadFromFile (server.MapPath(FileName)).Charset="GB2312".Position=2ReadText=.ReadText.Cancel().Close()end withset ads=nothingend functionsub SaveText(FileName,Data) '这是一个用于写文件的函数set fs= createobject("scripting.filesystemobject")set ts=fs.createtextfile(server.MapPath(FileName),true)ts.writeline(data)ts.closeset ts=nothingset fs=nothingend subsub toexcel(filename,sql) '这是一个根据SQL语句和FILENAME生成EXCEL文件Set rs=Server.CreateObject("ADODB.RecordSet")rs.Open sql,conn,1,3TOEXCELLR="<table width='100%'><tr >"set myfield=rs.fieldsdim fieldname(50)for i=0 to myfield.count-1toexcellr=toexcellr&"<td class=xl24>"&MYFIELD(I).NAME&"</td>"fieldname(i)=myfield(i).nameif myfield(i).type=135 then datename=datename&myfield(i).name&","nexttoexcellr=toexcellr&"</tr>"do while not rs.eoftoexcellr=toexcellr&"<tr>"for i=0 to myfield.count-1if instr(datename,fieldname(i)&",")<>0 thenif not isnull(rs(fieldname(i))) thenTOEXCELLR=TOEXCELLR&"<td class=xl25 ><p align='left'>"&formatdatetime(rs(fieldna me(i)),2)&"</p></td>"elseTOEXCELLR=TOEXCELLR&"<td class=xl25 ><p align='left'></p></td>"end ifelseTOEXCELLR=TOEXCELLR&"<td class=xl24 >"&rs(fieldname(i))&"</td>"end ifnexttoexcellr=toexcellr&"</tr>"rs.movenextlooptoexcellr=toexcellr&"</table>"tou=readtext("tou.txt")di=readtext("di.txt")toexcellr=tou&toexcellr&dicall savetext(filename,toexcellr)end sub%><html><head><meta http-equiv="refresh" content="3;URL=<%=filename%>"><meta http-equiv="Content-Language" content="en-us"><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>正在生成EXLCE文件</title></head><BODY>正在生成EXLCE文件....</BODY></HTML>**************第二个文件名为:di.txt 内容如下:<table x:str border=0 cellpadding=0 cellspacing=0 width=288 style='border-collapse: collapse;table-layout:fixed;width:216pt'><![if supportMisalignedColumns]><tr height=0 style='display:none'><td width=72 style='width:54pt'></td><td width=72 style='width:54pt'></td><td width=72 style='width:54pt'></td><td width=72 style='width:54pt'></td></tr><![endif]></table>************第三个文件的文件名为:tou.TXT内容如下:<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel"xmlns="/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=GB2312"><meta name=ProgId content=Excel.Sheet><meta name=Generator content="Microsoft Excel 9"><link rel=File-List href="./222.files/filelist.xml"><link rel=Edit-Time-Data href="./222.files/editdata.mso"><link rel=OLE-Object-Data href="./222.files/oledata.mso"><!--[if gte mso 9]><xml><o:DocumentProperties><o:Author>xky</o:Author><o:LastAuthor>xky</o:LastAuthor><o:Created>2002-05-27T17:51:00Z</o:Created><o:LastSaved>2002-06-22T10:03:03Z</o:LastSaved><o:Company>zydn</o:Company><o:Version>9.2812</o:Version></o:DocumentProperties><o:OfficeDocumentSettings><o:DownloadComponents/><o:LocationOfComponents HRef="file:///E:/msowc.cab"/></o:OfficeDocumentSettings></xml><![endif]--><style><!--table{mso-displayed-decimal-separator:"\."; mso-displayed-thousand-separator:"\,";} @page{margin:1.0in .75in 1.0in .75in;mso-header-margin:.5in;mso-footer-margin:.5in;}tr{mso-height-source:auto;mso-ruby-visibility:none;}col{mso-width-source:auto;mso-ruby-visibility:none;}br{mso-data-placement:same-cell;}.style0{mso-number-format:General;text-align:general;vertical-align:bottom;white-space:nowrap;mso-rotate:0;mso-background-source:auto;mso-pattern:auto;color:windowtext;font-size:9.0pt;font-weight:400;font-style:normal;text-decoration:none;font-family:宋体;mso-generic-font-family:auto;mso-font-charset:134;border:none;mso-protection:locked visible;mso-style-name:常规;mso-style-id:0;}td{mso-style-parent:style0;padding-top:1px;padding-right:1px;padding-left:1px;mso-ignore:padding;color:windowtext;font-size:9.0pt;font-weight:400;font-style:normal;text-decoration:none;font-family:宋体;mso-generic-font-family:auto; mso-font-charset:134;mso-number-format:General; text-align:general;vertical-align:bottom;border:none;mso-background-source:auto; mso-pattern:auto;mso-protection:locked visible; white-space:nowrap;mso-rotate:0;}.xl24{mso-style-parent:style0; border:.5pt solid windowtext;}.xl25{mso-style-parent:style0;mso-number-format:"Long Date"; text-align:left;border:.5pt solid windowtext;} ruby{ruby-align:left;}rt{color:windowtext;font-size:9.0pt;font-weight:400;font-style:normal;text-decoration:none;font-family:宋体;mso-generic-font-family:auto; mso-font-charset:134;mso-char-type:none;display:none;}--></style><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:DefaultRowHeight>225</x:DefaultRowHeight><x:Print><x:ValidPrinterInfo/><x:PaperSizeIndex>9</x:PaperSizeIndex><x:HorizontalResolution>-3</x:HorizontalResolution> <x:VerticalResolution>0</x:VerticalResolution></x:Print><x:Selected/><x:Panes><x:Pane><x:Number>3</x:Number><x:ActiveRow>24</x:ActiveRow><x:ActiveCol>5</x:ActiveCol></x:Pane></x:Panes><x:ProtectContents>False</x:ProtectContents><x:ProtectObjects>False</x:ProtectObjects><x:ProtectScenarios>False</x:ProtectScenarios></x:WorksheetOptions></x:ExcelWorksheet><x:ExcelWorksheet><x:Name>Sheet2</x:Name><x:WorksheetOptions><x:DefaultRowHeight>225</x:DefaultRowHeight><x:ProtectContents>False</x:ProtectContents><x:ProtectObjects>False</x:ProtectObjects><x:ProtectScenarios>False</x:ProtectScenarios></x:WorksheetOptions></x:ExcelWorksheet><x:ExcelWorksheet><x:Name>Sheet3</x:Name><x:WorksheetOptions><x:DefaultRowHeight>225</x:DefaultRowHeight><x:ProtectContents>False</x:ProtectContents><x:ProtectObjects>False</x:ProtectObjects><x:ProtectScenarios>False</x:ProtectScenarios></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets><x:WindowHeight>6600</x:WindowHeight><x:WindowWidth>12000</x:WindowWidth><x:WindowTopX>0</x:WindowTopX><x:WindowTopY>1395</x:WindowTopY><x:ProtectStructure>False</x:ProtectStructure><x:ProtectWindows>False</x:ProtectWindows></x:ExcelWorkbook></xml><![endif]--></head><body link=blue vlink=purple>上面的方法不用Excel支持,这对于虚拟主机来说很重要。