您好,登錄后才能下訂單哦!
怎么在ASP.Net中動(dòng)態(tài)讀取Excel文件?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
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(); } } //定時(shí)任務(wù) 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 是開源,跨平臺(tái),高性能,輕量級(jí)的 Web 應(yīng)用構(gòu)建框架,常用于通過(guò) HTML、CSS、JavaScript 以及服務(wù)器腳本來(lái)構(gòu)建網(wǎng)頁(yè)和網(wǎng)站。
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。