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
[Asp.net]C#操作Excel的几种方式优缺点比较
[]C#操作Excel的⼏种⽅式优缺点⽐较在项⽬中我们常常需要将数据库中的数据导出成Excel⽂件有⼀次⼯作中我的⽬的就是读取Excel到内存中,整理成指定格式整理后再导出到Excel。
因为我要处理的每个Excel表格⽂件很⼤。
⼀个表格多个sheet,每个sheet-⼀千到上W⾏不等。
列数超过300列。
所有在这⾥我将在使⽤⼀些处理Excel的⽅法的时候,所遇到的⼀些问题记录下来,也做⼀个⼤致的⽐较。
主要是针对此次数据处理NPOI⽬前⽐较流⾏的⼀款操作Excel的组件。
移植于Java的POI,是⼀个开源项⽬,对Excel的操作很全⾯。
官⽹优势:1、免费2、机器不⽤安装Office也可以直接操作Excel,免去很多事。
3、现在已⾄此的⽂件格式包括Excel2003和2007之后的xls,xlsx以及docx。
4、⽀持⽂件的导⼊和导出5、⽹上有丰富的实例代码,遇到基本的问题可以上⽹参考⽹友的解决⽅法。
6、NPOI能⽀持绝⼤多数Excel⾥⾯的功能操作(Excel内的公式函数、设置单元格的格式样式)7、导⼊导出速度快。
内存占⽤⼤。
特定优势:⽀持读取超过256列的Excel表格。
缺点:参考⽬前很多⽹上的⽂档,npoi导出xlsx,使⽤ XSSFWorkbook 使⽤ Write ⽅法写⼊内存流后,返回的 MemoryStream 已经被关闭了,不能再使⽤了。
你需要花⼀点时间解决这个问题。
可以参考:xlsx格式导出推荐使⽤Epplus组件NPOI辅助类:1 using System;2 using System.Collections;3 using System.Collections.Generic;4 using System.Text;5 using System.IO;6 using System.Data;7 using System.Windows.Forms;8 using erModel;9 using erModel;10 using erModel;1112 namespace TEMS.Service13 {14 public static class ExcelHelperForCs15 {16 #region 私有⽅法1718 /// <summary>19 /// 获取要保存的⽂件名称(含完整路径)20 /// </summary>21 /// <returns></returns>22 private static string GetSaveFilePath()23 {24 SaveFileDialog saveFileDig = new SaveFileDialog();25 saveFileDig.Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";26 saveFileDig.FilterIndex = 0;28 saveFileDig.OverwritePrompt = true;29 saveFileDig.InitialDirectory = Common.DesktopDirectory;30 string filePath = null;31 if (saveFileDig.ShowDialog() == DialogResult.OK)32 {33 filePath = saveFileDig.FileName;34 }3536 return filePath;37 }3839 /// <summary>40 /// 获取要打开要导⼊的⽂件名称(含完整路径)41 /// </summary>42 /// <returns></returns>43 private static string GetOpenFilePath()44 {45 OpenFileDialog openFileDig = new OpenFileDialog();46 openFileDig.Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";47 openFileDig.FilterIndex = 0;48 openFileDig.Title = "打开";49 openFileDig.CheckFileExists = true;50 openFileDig.CheckPathExists = true;51 openFileDig.InitialDirectory = Common.DesktopDirectory;52 string filePath = null;53 if (openFileDig.ShowDialog() == DialogResult.OK)54 {55 filePath = openFileDig.FileName;56 }5758 return filePath;59 }6061 /// <summary>62 /// 判断是否为兼容模式63 /// </summary>64 /// <param name="filePath"></param>65 /// <returns></returns>66 private static bool GetIsCompatible(string filePath)67 {68 return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);69 }7071 /// <summary>72 /// 创建⼯作薄73 /// </summary>74 /// <param name="isCompatible"></param>75 /// <returns></returns>76 private static IWorkbook CreateWorkbook(bool isCompatible)77 {78 if (isCompatible)79 {80 return new HSSFWorkbook();81 }82 else83 {84 return new XSSFWorkbook();85 }86 }8788 /// <summary>89 /// 创建⼯作薄(依据⽂件流)90 /// </summary>91 /// <param name="isCompatible"></param>92 /// <param name="stream"></param>93 /// <returns></returns>94 private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)95 {96 if (isCompatible)97 {98 return new HSSFWorkbook(stream);99 }100 else101 {102 return new XSSFWorkbook(stream);103 }104 }105106 /// <summary>107 /// 创建表格头单元格108 /// </summary>109 /// <param name="sheet"></param>110 /// <returns></returns>111 private static ICellStyle GetCellStyle(IWorkbook workbook)112 {113 ICellStyle style = workbook.CreateCellStyle();114 style.FillPattern = FillPattern.SolidForeground;115 style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;116117 return style;118 }120 /// <summary>121 /// 从⼯作表中⽣成DataTable122 /// </summary>123 /// <param name="sheet"></param>124 /// <param name="headerRowIndex"></param>125 /// <returns></returns>126 private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex) 127 {128 DataTable table = new DataTable();129130 IRow headerRow = sheet.GetRow(headerRowIndex);131 int cellCount = stCellNum;132133 for (int i = headerRow.FirstCellNum; i < cellCount; i++)134 {135 if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "") 136 {137 // 如果遇到第⼀个空列,则不再继续向后读取138 cellCount = i;139 break;140 }141 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); 142 table.Columns.Add(column);143 }144145 for (int i = (headerRowIndex + 1); i <= stRowNum; i++)146 {147 IRow row = sheet.GetRow(i);148 //如果遇到某⾏的第⼀个单元格的值为空,则不再继续向下读取149 if (row != null && !string.IsNullOrEmpty(row.GetCell(0).ToString()))150 {151 DataRow dataRow = table.NewRow();152153 for (int j = row.FirstCellNum; j < cellCount; j++)154 {155 dataRow[j] = row.GetCell(j).ToString();156 }157158 table.Rows.Add(dataRow);159 }160 }161162 return table;163 }164165 #endregion166167 #region 公共导出⽅法168169 /// <summary>170 /// 由DataSet导出Excel171 /// </summary>172 /// <param name="sourceTable">要导出数据的DataTable</param>173 /// <returns>Excel⼯作表</returns>174 public static string ExportToExcel(DataSet sourceDs, string filePath = null)175 {176177 if (string.IsNullOrEmpty(filePath))178 {179 filePath = GetSaveFilePath();180 }181182 if (string.IsNullOrEmpty(filePath)) return null;183184 bool isCompatible = GetIsCompatible(filePath);185186 IWorkbook workbook = CreateWorkbook(isCompatible);187 ICellStyle cellStyle = GetCellStyle(workbook);188189 for (int i = 0; i < sourceDs.Tables.Count; i++)190 {191 DataTable table = sourceDs.Tables[i];192 string sheetName = "result" + i.ToString();193 ISheet sheet = workbook.CreateSheet(sheetName);194 IRow headerRow = sheet.CreateRow(0);195 // handling header.196 foreach (DataColumn column in table.Columns)197 {198 ICell cell = headerRow.CreateCell(column.Ordinal);199 cell.SetCellValue(column.ColumnName);200 cell.CellStyle = cellStyle;201 }202203 // handling value.204 int rowIndex = 1;205206 foreach (DataRow row in table.Rows)207 {208 IRow dataRow = sheet.CreateRow(rowIndex);209210 foreach (DataColumn column in table.Columns)212 dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString());213 }214215 rowIndex++;216 }217 }218219 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);220 workbook.Write(fs);221 fs.Dispose();222 workbook = null;223224 return filePath;225226 }227228 /// <summary>229 /// 由DataTable导出Excel230 /// </summary>231 /// <param name="sourceTable">要导出数据的DataTable</param>232 /// <returns>Excel⼯作表</returns>233 public static string ExportToExcel(DataTable sourceTable, string sheetName = "result", string filePath = null)234 {235 if (sourceTable.Rows.Count <= 0) return null;236237 if (string.IsNullOrEmpty(filePath))238 {239 filePath = GetSaveFilePath();240 }241242 if (string.IsNullOrEmpty(filePath)) return null;243244 bool isCompatible = GetIsCompatible(filePath);245246 IWorkbook workbook = CreateWorkbook(isCompatible);247 ICellStyle cellStyle = GetCellStyle(workbook);248249 ISheet sheet = workbook.CreateSheet(sheetName);250 IRow headerRow = sheet.CreateRow(0);251 // handling header.252 foreach (DataColumn column in sourceTable.Columns)253 {254 ICell headerCell = headerRow.CreateCell(column.Ordinal);255 headerCell.SetCellValue(column.ColumnName);256 headerCell.CellStyle = cellStyle;257 }258259 // handling value.260 int rowIndex = 1;261262 foreach (DataRow row in sourceTable.Rows)263 {264 IRow dataRow = sheet.CreateRow(rowIndex);265266 foreach (DataColumn column in sourceTable.Columns)267 {268 dataRow.CreateCell(column.Ordinal).SetCellValue((row[column]??"").ToString());269 }270271 rowIndex++;272 }273 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);274 workbook.Write(fs);275 fs.Dispose();276277 sheet = null;278 headerRow = null;279 workbook = null;280281 return filePath;282 }283284 /// <summary>285 /// 由List导出Excel286 /// </summary>287 /// <typeparam name="T">类型</typeparam>288 /// <param name="data">在导出的List</param>289 /// <param name="sheetName">sheet名称</param>290 /// <returns></returns>291 public static string ExportToExcel<T>(List<T> data, IList<KeyValuePair<string, string>> headerNameList, string sheetName = "result", string filePath = null) where T : class 292 {293 if (data.Count <= 0) return null;294295 if (string.IsNullOrEmpty(filePath))296 {297 filePath = GetSaveFilePath();298 }299300 if (string.IsNullOrEmpty(filePath)) return null;301302 bool isCompatible = GetIsCompatible(filePath);304 IWorkbook workbook = CreateWorkbook(isCompatible);305 ICellStyle cellStyle = GetCellStyle(workbook);306 ISheet sheet = workbook.CreateSheet(sheetName);307 IRow headerRow = sheet.CreateRow(0);308309 for (int i = 0; i < headerNameList.Count; i++)310 {311 ICell cell = headerRow.CreateCell(i);312 cell.SetCellValue(headerNameList[i].Value);313 cell.CellStyle = cellStyle;314 }315316 Type t = typeof(T);317 int rowIndex = 1;318 foreach (T item in data)319 {320 IRow dataRow = sheet.CreateRow(rowIndex);321 for (int n = 0; n < headerNameList.Count; n++)322 {323 object pValue = t.GetProperty(headerNameList[n].Key).GetValue(item, null);324 dataRow.CreateCell(n).SetCellValue((pValue ?? "").ToString());325 }326 rowIndex++;327 }328 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);329 workbook.Write(fs);330 fs.Dispose();331332 sheet = null;333 headerRow = null;334 workbook = null;335336 return filePath;337 }338339 /// <summary>340 /// 由DataGridView导出341 /// </summary>342 /// <param name="grid"></param>343 /// <param name="sheetName"></param>344 /// <param name="filePath"></param>345 /// <returns></returns>346 public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null) 347 {348 if (grid.Rows.Count <= 0) return null;349350 if (string.IsNullOrEmpty(filePath))351 {352 filePath = GetSaveFilePath();353 }354355 if (string.IsNullOrEmpty(filePath)) return null;356357 bool isCompatible = GetIsCompatible(filePath);358359 IWorkbook workbook = CreateWorkbook(isCompatible);360 ICellStyle cellStyle = GetCellStyle(workbook);361 ISheet sheet = workbook.CreateSheet(sheetName);362363 IRow headerRow = sheet.CreateRow(0);364365 for (int i = 0; i < grid.Columns.Count; i++)366 {367 ICell cell = headerRow.CreateCell(i);368 cell.SetCellValue(grid.Columns[i].HeaderText);369 cell.CellStyle = cellStyle;370 }371372 int rowIndex = 1;373 foreach (DataGridViewRow row in grid.Rows)374 {375 IRow dataRow = sheet.CreateRow(rowIndex);376 for (int n = 0; n < grid.Columns.Count; n++)377 {378 dataRow.CreateCell(n).SetCellValue((row.Cells[n].Value ?? "").ToString());379 }380 rowIndex++;381 }382383 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);384 workbook.Write(fs);385 fs.Dispose();386387 sheet = null;388 headerRow = null;389 workbook = null;390391 return filePath;392 }393394 #endregion396 #region 公共导⼊⽅法397398 /// <summary>399 /// 由Excel导⼊DataTable400 /// </summary>401 /// <param name="excelFileStream">Excel⽂件流</param>402 /// <param name="sheetName">Excel⼯作表名称</param>403 /// <param name="headerRowIndex">Excel表头⾏索引</param>404 /// <param name="isCompatible">是否为兼容模式</param>405 /// <returns>DataTable</returns>406 public static DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible) 407 {408 IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);409 ISheet sheet = null;410 int sheetIndex = -1;411 if (int.TryParse(sheetName, out sheetIndex))412 {413 sheet = workbook.GetSheetAt(sheetIndex);414 }415 else416 {417 sheet = workbook.GetSheet(sheetName);418 }419420 DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);421422 excelFileStream.Close();423 workbook = null;424 sheet = null;425 return table;426 }427428 /// <summary>429 /// 由Excel导⼊DataTable430 /// </summary>431 /// <param name="excelFilePath">Excel⽂件路径,为物理路径。
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表在客客户端显示。
ASP读取xls格式的Excel文件
ASP读取xls格式的Excel文件2011年6月28日ASP12 评论Excel也是一种数据库,跟Access类似,其读取方法也类似。
这里有一个简单的Excel表,文件名字为Excel.xls:咱就这个为例子来说明。
创建Excel连接代码:Dim XlsConn,xrsSet XlsConn=Server.CreateO bject("Adodb.Connection")XlsConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Server.MapPath("Excel.xls")&";Extended Properties=Excel 8.0" 是不是跟连接Access文件很像呢?呵呵~连接创建好了,就可以创建记录集查询Excel里面的数据了。
Set xrs=XlsConn.Execute("Select * From [Sheet1$]")跟其他数据库的查询几乎是一样的,要注意的地方就是表名,Excel里面,默认会有三张表,Sheet1、Sheet2、Sheet3,从上面的例子也可以看到,需要注意查询时表名后面要加“$”符;查询结果:xrs(0)="数据列0"xrs(1)="1"xrs(2)="2"xrs(3)="3"xrs(4)="4"xrs(5)="5"这里有一点需要注意,如果一列中有多行,有的行的值是数字,有的行是字符,ASP去取值的时候数字行会读取出错,是为空的。
所以得想办法把数字行也变成字符型,比如加个’号去,读取出来之后再替换回去。
多行自然是用xrs.Movenext去循环取得了。
够简单吧!最后贴一段代码:Dim rsSet rs=Server.CreateObject("Adodb.Recordset")rs.Open "Select Top 1 * From Pro Where 1=2",Conn,3,2Dim XlsConn,xrsSet XlsConn=Server.CreateO bject("Adodb.Connection")XlsConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Server.MapPath("Excel.xls")&";Extended Properties=Excel 8.0"Set xrs=XlsConn.Execute("Select * From [Sheet1$]")Do While Not xrs.Eofrs.Addnewrs("iClear")= xrs(0)rs("Detail")= xrs(1)rs.Updatexrs.MovenextLoopxrs.Close()Set xrs=NothingXlsConn.Close()Set XlsConn=Nothingrs.Close()Set rs=NothingASP操作xls文件(2005-11-10 14:15:12)转载▼标签:杂谈分类:ASP只写一种方法。
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中的数据导⼊数据库asp实现excel中的数据导⼊数据库<% Response.CodePage=65001%><% Response.Charset="UTF-8" %><%wenjian = request.Form("select")'获取⽂件扩展名ext = FileExec(wenjian)'判断⽂件扩展名if ext <> "xls" thenresponse.Write("<script>alert('⽂件类型不对,请核实!');window.location.href='index.html';</script>")response.End()end ifDim objConn,objRSDim strConn,strSqlset objConn=Server.CreateObject("ADODB.Connection")set objRS=Server.CreateObject("ADODB.Recordset")excelFile = server.mappath(wenjian)'针对excel 2007strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & excelFile & ";" & "Extended Properties=Excel 8.0;"objConn.Open strConnstrSql="SELECT * FROM [Sheet1$]"objRS.Open strSql,objConn,1,1objRS.MoveFirst%><!--#include file="conn.asp"--><%'循环excel中所有记录while not objRS.eofset rs = Server.CreateObject("Adodb.Recordset")'查询语句sql_s = "select * from ceshi where lname='" & objRS(0) & "' and old='" & objRS(1) & "' and sex='" & objRS(2) & "' and guojia='" & objRS(3) & "' and QQ='" & objRS(4) & "'" rs.open sql_s, conn, 1, 1'重复的数据不做录⼊操作if rs.eof then'插⼊语句'****excel中第⼀条不会被录⼊****sql = "insert into ceshi (lname, old, sex, guojia, QQ)values ('" & objRS(0) & "', '" & objRS(1) & "', '" & objRS(2) & "', '" & objRS(3) & "', '" & objRS(4) & "')"'执⾏插⼊conn.execute(sql)end ifobjRS.MoveNextrs.closeset rs = nothingwend'⼜到了各种关闭的时候conn.closeset conn = nothingobjRS.CloseobjConn.Closeset objRS = Nothingset objConn = Nothingresponse.Write("<script>alert('导⼊成功');window.location.href='index.html';</script>")response.End()Function FileExec(fileName)FileExec = Mid(fileName,Instr(fileName,".")+1,Len(fileName)-Instr(fileName,"."))End Function%>再分享⼀个简化版的代码wenjian=request.Form("floor")fileext=mid(wenjian,InStrRev(wenjian,".")+1)if lcase(fileext)<>"xls" thenresponse.write "<script>alert ('⽂件格式不对,请上传Excel⽂件');window.location.href='updateFloor.asp';</script>"response.endend ifset conne=server.CreateObject("ADODB.Connection")connStre="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath( ""&wenjian&"" )&";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"conne.open connStreSqle="select * from [sheet1$] "Set rse = Server.CreateObject("ADODB.Recordset")rse.open sqle,conne,1,1'验证hang=2do while not rse.eof'名称不能为空if trim(rse(0))<>"" thenelsemess="第"& hang &"⾏名称为空,请检查!"response.Write"<script>alert('"& mess &"').window.location.href='updateFloor.asp'</script>"response.End()end ifrse.movenexthang=hang+1looprse.movefirstdo while not rse.eofset rst=server.CreateObject("adodb.recordset")sqlt="select * from Sellman"rst.open sqlt,conn,1,3rst.addnew()rst("CompanyName")=c2(rse(0))rst("CompanyInfo")=c2(rse(1))rst("address")=c2(rse(2))rst("tel")=c2(rse(3))&" "&c2(rse(7))rst("Fax")=c2(rse(4))rst("linkman")=c2(rse(5))rst("Homepage")=c2(rse(8))rst("Email")=c2(rse(6))rst.update()rst.closeset rst=nothingrse.movenextlooprse.closeset rse=nothingresponse.Write "<script>alert('导⼊成功!');location.href='updateFloor.asp';</script>"其实简单的说象access 数据库⼀样,把excel⽂件打开,再进⾏读再写到access中你要写到sqlserver中就把写的过程改⼀下就成了看下代码:dim conndim conn2set conn=CreateObject("ADODB.Connection")conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:\book1.mdb"set conn2=CreateObject("ADODB.Connection")conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=c:\book1.xls"sql = "SELECT * FROM [Sheet1$]"set rs = conn2.execute(sql)while not rs.eofsql = "insert into xxx([a],[b],[c],[d]) values('"& fixsql(rs(0)) &"','"& fixsql(rs(1)) &"','"& fixsql(rs(2)) &"','"& fixsql(rs(3)) &"')"conn.execute(sql)rs.movenextwendconn.closeset conn = nothingconn2.closeset conn2 = nothingfunction fixsql(str)dim newstrnewstr = strif isnull(newstr) thennewstr = ""elsenewstr = replace(newstr,"'","''")end iffixsql = newstrend function。
ASP导出为Word或Excel的最简单方法
ASP导出为Word或Excel的最简单方法2010-09-04 15:05方法1:把一个Word文档另存为XML格式(可能需要Office2003才能支持),然后你就可以用操作XML文件的方法,来对这个文件中指定的文字替换成你需要的内容。
重新打开这个文件,你会发现它是在Word中打开的,这样可以用Word来继续编辑或者打印。
方法2:我在做一项目时,客户要求要将从数据库中获取数据后的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:solidwindowtext .5pt;5.mso-yfti-tbllook:480;mso-padding-alt:0cm 5.4pt 0cm5.4pt;mso-border-insideh:6..5pt solid windowtext;mso-border-insidev:.5pt solidwindowtext;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:solidwindowtext 1.0pt;11.mso-border-top-alt:solidwindowtext .5pt;mso-border-left-alt:solid windowtext .5pt;12.mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm5.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:1pxdotted #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的探讨与实现
根据用户的要求需要将数据打印出来, 而通常 匝 自
带的打印功能一般不能满足该需求。据于此, 本文 探讨并实践了 A P网络应用程序 中将数据导 出至 S E C L报表 中, X E 方便用户编辑与打印。按照应用需
求,S A P网络应用程序 实现该功 能通 常有两种 情
况:
发的数据访 问技术, 是一个用于存取数据源的 C M O 组件,它提供了编程语 言和统一数 据访 问方式, 与 O ED L B一起协 同工作, 以提供通用数据访 问, 是一 种功能强大的数据访 问编程模式,是对当前微软所
关键词 : P A AS ; DO; 数据 导 出 ; XC L报 表 E E
中 图分 类号 :P 1 T 3 l 文献 标识 码 : A 文章编号 :6 14 9 . O O1 .0 60 17 .7 2( )10 1.3 2L
Ab tac : s d O tB/ d ,t P b a plc t ns d t u p tt s r tBa e F S mo e he AS we p ia i aa o t u o EXCEL e e a e r p rs e p o e o g n r t e o t x l r s m eh sa r c ie o v d t e AS wrt t o k a lc to st e e n aa o t u o EXCEL e e a er — t od nd p a tc .s l e h P i new r pp ia i n o r lva td t u p tt e g n r t e
一
AS ( t e e e ae 即动态 服 务器 页面 , PAci r r g) vS v P 是 套 由微软公司开发的服务器端脚 本编写环境, 使
ASP连接excel的方法
asp连接Excel的方法一、asp连接Excel的方法与代码:<%dim connxls,connstrxlsconnstrxls="DBQ=d:\newexcel.xls;DefaultDir=;DRIVER={Microsoft Excel Driver (*.xls)};"Set connxls=Server.CreateObject("ADODB.Connection")connxls.Open connstrxlsSet rsxls=Server.CreateObject("ADODB.Recordset")SQLxls = "select * from [new$]"%>注意:写法和连接ACCESS基本相同,不同的是,在调用工作表的时候,不能直接用表名,工作表名后要加$,而且要用“[]”括起来。
二、asp操作Excel的总结:1、建立Excel对象setobjExcelApp=CreateObject("Excel.Application")objExcelApp.DisplayAlerts=false不显示警告objExcelApp.Application.Visible=false不显示界面2、新建Excel文件objExcelApp.WorkBooks.addsetobjExcelBook=objExcelApp.ActiveWorkBooksetobjExcelSheets=objExcelBook.WorksheetssetobjExcelSheet=objExcelBook.Sheets(1)3、读取已有Excel文件strAddr=Server.MapPath(".")objExcelApp.WorkBooks.Open(strAddr&"\Templet\Table.xls")Set objExcelBook=objExcelApp.ActiveWorkBookSet objExcelSheets=objExcelBook.WorksheetsSet objExcelSheet=objExcelBook.Sheets(1)4、另存Excel文件objExcelBook.SaveAsstrAddr&"\Temp\Table.xls"5、保存Excel文件objExcelBook.Save(笔者测试时保存成功,页面报错。
ASP.NET之Excel下载模板、导入、导出操作
之Excel下载模板、导⼊、导出操作本⽂介绍了下Excel下载模板、导⼊、导出操作,供⼤家参考,具体内容如下1.下载模板功能protected void btnDownload_Click(object sender, EventArgs e){var path = Server.MapPath(("upfiles\\") + "test.xlt"); //upfiles-⽂件夹 test.xlt-⽂件var name = "test.xlt";try{var file = new FileInfo(path);Response.Clear();Response.Charset = "GB2312";Response.ContentEncoding = System.Text.Encoding.UTF8;Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //头信息,指定默认⽂件名Response.AddHeader("Content-Length", file.Length.ToString());//显⽰下载进度Response.ContentType = "application/ms-excel"; // 指定返回的是⼀个不能被客户端读取的流,必须被下载Response.WriteFile(file.FullName); // 把⽂件流发送到客户端pleteRequest();}catch (Exception ex){Response.Write("<script>alert('错误:" + ex.Message + ",请尽快与管理员联系')</script>");}}2.导⼊数据Excel数据导⼊到数据库中。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 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支持,这对于虚拟主机来说很重要。