您好,登錄后才能下訂單哦!
怎么在ASP.Net中動態讀取Excel文件?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
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 以及服務器腳本來構建網頁和網站。
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。