ASP.NET中上传并读取Excel文件数据示例_6
点聚weboffice 6.0 ASP.NET 在线Word,excel,wps编辑控件

点聚weboffice 6.0 在线Word,excel,wps编辑控件WebOffice是一款由北京点聚信息技术有限公司提供的完全免费(商业用途也免费)且功能强大的在线Word/excel/wps编辑辅助控件,可以实现:1.在线编辑Word、Excel、PPT、WPS... ...2.全面支持MS Office的界面定制,包括对于Office2007的全面支持3.修订留痕4.限制打印、保存、复制5.直接保存到服务器,支持标准Http Post协议6.强大的书签管理7.套红、文档保护8.模板管理9.其他功能扩展点聚WebOffice是基于客户端的ocx控件,它的功能是将Office文档(Word、Excel、WPS)嵌入到浏览器中,并调用Office中各种接口,完成文档编辑工作,然后使用控件的Http 接口模拟表单提交,发送到数据处理页面(此文档举例为saveDoc.asp页,代码见演示文件),完成文档的存档工作。
在本地测试的时后,首先要安装插件和证书WebOffice_Setup.exe和孙小钢.pfx,然后用VS来运行示例,不要直接打开HTML,那样会报错的webOffice控件自动下载是指在打开网页时,网页会自动把webOffice控件下载下来,从而可以将word、excel嵌入到网页中。
控件自动下载的相关代码如下:< object id=WebOffice height=768 width="100%"style="LEFT: 0px; TOP: 0px"classid="clsid:E77E049B-23FC-4DB8-B756-60529A35FAD5" codebase="../js/WebOffice1.ocx#version=6,0,4,0"><param name="_ExtentX" value="6350"><param name="_ExtentY" value="6350">object>上面的脚本意思是:自动更新classid=FF1FE7A0-0578-4FEE-A34E-FB21B277D561 的COM组件,更新地址为../js/WebOffice1.ocx,codebase后的路径为相对路径也可为绝对路径,要更新的最新版本为6,0,4,0。
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.NET中GridView读取Excel数据的实现

中图分类号 T 3 2 P 9
G iVe r i d w显示控件
文献标识码 B 文 章 编 号 1 3 0 5 1 0 3 — 7 1 9
Th a ia i n o iV w a t r m x e i ASP. e Re l t f d J Re d Da a fO E c ln z o Gr e NET
用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数据的四种方法

ASP导出Excel数据的四种方法一、使用OWC什么是OWC?OWC是Office Web Compent的缩写,即Microsoft的Office Web组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。
在一个intranet环境中,如果可以假设客户机上存在特定的浏览器和一些功能强大的软件(如IE5和Office 2000),那么就有能力利用Office Web组件提供一个交互式图形开发环境。
这种模式下,客户端工作站将在整个任务中分担很大的比重。
<%Option ExplicitClass ExcelGenPrivate objSpreadsheetPrivate iColOffsetPrivate iRowOffsetSub Class_Initialize()Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet")iRowOffset = 2iColOffset = 2End SubSub Class_Terminate()Set objSpreadsheet = Nothing "Clean up End SubPublic Property Let ColumnOffset(iColOff) If iColOff > 0 theniColOffset = iColOffElseiColOffset = 2End IfEnd PropertyPublic Property Let RowOffset(iRowOff) If iRowOff > 0 theniRowOffset = iRowOffElseiRowOffset = 2End IfEnd Property Sub GenerateWorksheet(objRS)"Populates the Excel worksheet based on a Recordset"s contents"Start by displaying the titlesIf objRS.EOF then Exit SubDim objField, iCol, iRowiCol = iColOffsetiRow = iRowOffsetFor Each objField in objRS.FieldsobjSpreadsheet.Cells(iRow, iCol).Value = /doc/71b0b63383c4bb4cf7ecd11a.htmlobjSpreadsheet.Columns(iCol).AutoFitColumns"设置Excel表里的字体objSpreadsheet.Cells(iRow, iCol).Font.Bold = True objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10 objSpreadsheet.Cells(iRow, iCol).Halignment = 2 "居中iCol = iCol + 1Next "objField"Display all of the dataDo While Not objRS.EOFiRow = iRow + 1iCol = iColOffsetFor Each objField in objRS.FieldsIf IsNull(objField.Value) thenobjSpreadsheet.Cells(iRow, iCol).Value = ""ElseobjSpreadsheet.Cells(iRow, iCol).Value = objField.Value objSpreadsheet.Columns(iCol).AutoFitColumns objSpreadsheet.Cells(iRow, iCol).Font.Bold = False objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10End IfiCol = iCol + 1Next "objFieldobjRS.MoveNextLoopEnd Sub Function SaveWorksheet(strFileName)"Save the worksheet to a specified filenameOn Error Resume NextCall objSpreadsheet.ActiveSheet.Export(strFileName, 0)SaveWorksheet = (Err.Number = 0)End FunctionEnd ClassDim objRSSet objRS = Server.CreateObject("ADODB.Recordset")objRS.Open "SELECT * FROM xxxx", "Provider=SQLOLEDB.1;Persist SecurityInfo=True;User ID=xxxx;Password=xxxx;Initial Catalog=xxxx;Data source=xxxx;"Dim SaveNameSaveName = Request.Cookies("savename")("name")Dim objExcelDim ExcelPathExcelPath = "Excel\" & SaveName & ".xls"Set objExcel = New ExcelGenobjExcel.RowOffset = 1objExcel.ColumnOffset = 1objExcel.GenerateWorksheet(objRS)If objExcel.SaveWorksheet(Server.MapPath(ExcelPath)) then "Response.Write "已保存为Excel文件.下载"ElseResponse.Write "在保存过程中有错误!"End IfSet objExcel = NothingobjRS.CloseSet objRS = Nothing%>二、用Excel的Application组件在客户端导出到Excel或Word 注意:两个函数中的“data“是网页中要导出的table的 id导出到Excel代码导出到Word代码三、直接在IE中打开,再存为EXCEL文件把读出的数据用格式,在网页中显示出来,同时,加上下一句即可把EXCEL表在客客户端显示。
ASP导入Excel表格

201412261323_ASP导入Excel表格导入EXCEL表格常用于批处理数据或者数据迁移项目。
导入代码如下:<!--#include file="conn.asp" --><%Set ConnExcel=Server.CreateObject("ADODB.Connection")'--利用Open 方法打开数据库StrExcelConn="Driver={Microsoft Excel Driver (*.xls)};"&"DriverId=790; DBQ="&Server.MapPath("card.xls") 'EXCEL文件路径ConnExcel.Open StrExcelConn'--建立数据集对象Rs并查询数据Set Rs = Server.CreateObject("ADODB.Recordset")Sql="select * from [default$]" '特别注意EXCEL表名要一致rs.Open Sql,ConnExcel,1,1do while not rs.eofrsx=server.createobject("adodb.recordset")setsqlx="select * from pcard"sqlx,conn,1,3rsx.openrsx.addnewrsx("cardnum")=rs(0)rsx("cardpwd")=rs(1)rsx("cardpay")=cint(rs(2))rsx.updatersx.closersx=nothingsetrs.MoveNextlooprs.closeset rs=nothingConnExcel.closeset ConnExcel=nothingCall Closeconn()response.write "<script language=JavaScript>"response.Write "alert('导入成功!'); "response.Write "</script>"Response.end()%>人生最精彩的不是实现梦想的瞬间,而是坚持梦想的过程。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
如何打开Excel数据库文件,想必有很多朋友都不清楚吧,下面通过一个简单的例子,实现读取Excel数据文件
在CSDN中,经常有人问如何打开Excel数据库文件。
本文通过一个简单的例子,实现读取Excel数据文件。
首先,创建一个Web应用程序项目,在Web页中添加一个DataGrid控件、一个文件控件和一个按钮控件。
代码如下:
<INPUTid="File1"type="file"name="File1"runat="server">
<asp:Buttonid="Button1"runat="server"Text="Button"></asp:Button>
<asp:DataGridid="DataGrid1"runat="server"></asp:DataGrid>
在代码视图中首先导入OleDb命名空间:
usingSystem.Data.OleDb;
在按钮的单击事件中输入如下代码:
代码如下:
stringstrPath="c://test//"+DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";
File1.PostedFile.SaveAs(strPath);
stringmystring="Provider=Microsoft.Jet.OLEDB.4.0;DataSource='"+strPath+"';ExtendedPropertie s=Excel8.0";
OleDbConnectioncnnxls=newOleDbConnection(mystring);
OleDbDataAdaptermyDa=newOleDbDataAdapter("select*from[Sheet1$]",cnnxls);
DataSetmyDs=newDataSet();
myDa.Fill(myDs);
DataGrid1.DataSource=myDs.Tables[0];
DataGrid1.DataBind();
其中C:/test对ASPNET用户要有读写的权限.
更多信息请查看IT技术专栏。