重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
怎么在ASP.Net中动态读取Excel文件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
云梦ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!
Default.aspx.cs代码:
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { delete(); } protected void Button1_Click(object sender, EventArgs e) { OleDbConnection conn = new OleDbConnection(); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); DataSet ds = new DataSet(); string query = null; string connString = ""; string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss"); //string strFileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string strFileType = Path.GetExtension(FileUpload1.FileName).ToString().ToLower(); if (strFileType == ".xls" || strFileType == ".xlsx") { FileUpload1.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType)); } else { return; } string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType); if (strFileType.Trim() == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; } else if (strFileType.Trim() == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; } query = "SELECT * FROM [Sheet1$]"; conn = new OleDbConnection(connString); if (conn.State == ConnectionState.Closed) { conn.Open(); } try { cmd = new OleDbCommand(query, conn); da = new OleDbDataAdapter(cmd); ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); Label1.Text = "读取成功"; } catch (Exception ex) { Label1.Text = "读取失败"; Response.Write(ex); } finally { da.Dispose(); conn.Close(); conn.Dispose(); } } //定时任务 private void delete() { DirectoryInfo di = new DirectoryInfo(Server.MapPath("/UploadedExcel/")); FileInfo[] fi = di.GetFiles("*." + "*"); DateTime dtNow = DateTime.Now; foreach (FileInfo tmpfi in fi) { TimeSpan ts = dtNow.Subtract(tmpfi.LastWriteTime); if (ts.Milliseconds > 100) { tmpfi.Attributes = FileAttributes.Normal; tmpfi.Delete(); } } } } }
ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。