前台頁面
<div style="text-align: right;"> 序列號信息: <asp:FileUpload ID="FileSN" runat="server" /> <asp:Button ID="btnSN" runat="server" Text="上傳" OnClick="btnSN_Click" /> </div>
后台代碼
添加引用 using System.IO;
protected void btnSN_Click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(file.PostedFile.FileName)) { //獲取上傳文件擴展名稱 string FullName = file.PostedFile.FileName; if (!(FullName.IndexOf(".xlsx") > 0 || FullName.IndexOf(".xls") > 0))//判斷上傳文件是否為Excel文件 throw new Exception("上傳文件需為EXCEL格式!"); FileInfo FileInfo = new FileInfo(FullName); string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + FileInfo.Name;//定義文件名 string pathws = ConfigurationManager.AppSettings["SNFileWs"].ToString();//發布的文件路徑 string path = ConfigurationManager.AppSettings["SNFile"].ToString();//保存在本地的文件路徑 if (!Directory.Exists(path)) Directory.CreateDirectory(path);//如果本地不存在路徑Path,則創建路徑Path file.PostedFile.SaveAs(path + "\\" + FileName);//保存文件內容 string NewFileName = FileName; string FilePath = pathws + "\\" + FileName; string UpdateTime = DateTime.Now.ToString(); int Status = (int)enumDealerFileState.FilePass; string UserId = WebUtility.GetCurrentUserId().ToString(); DataTable dt = ExcelToDataTable(path + "\\" + FileName, "Sheet1", true);//將Excel文件內容轉換為DataTable string PK_StoreSNFile = StoreSNDAL.InsertStoreSNFile(UserId, FileInfo.Name, NewFileName, DateTime.Now.ToString(), FilePath, Status); StringBuilder SqlStr = new StringBuilder(); for (int i = 0; i < dt.Rows.Count; i++) { SqlStr.Append(InsertStr(PK_StoreSNFile, dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString())); } StoreSNDAL.InsertStoreSNFileDataByStr(SqlStr); Response.Write("<script>alert('上傳成功。')</script>"); } else { Response.Write("<script>alert('請選擇上傳文件。')</script>"); } } catch (Exception ex) { CustomValidator1.IsValid = false; CustomValidator1.ErrorMessage = ex.Message; } } /// <summary> /// 將Excel文件的內容保存到DataTable /// </summary> /// <param name="fileName">文件完整路徑</param> /// <param name="sheetName">指定讀取excel工作薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名:true=是,false=否</param> /// <returns>DataTable數據表</returns> public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn) { string HDR = string.Empty;//如果第一行是數據而不是標題的話, 應該寫: "HDR=No;" if (isFirstRowColumn) { HDR = "YES";//第一行是標題 } else { HDR = "NO";//第一行是數據 } //源的定義 string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + fileName + ";" + "Extended Properties='Excel 8.0;HDR=" + HDR + ";IMEX=1';"; //Sql語句 string strExcel = "select * from [" + sheetName + "$]"; //定義存放的數據表 DataSet ds = new DataSet(); //連接數據源 using (OleDbConnection conn = new OleDbConnection(strConn)) { try { conn.Open(); //適配到數據源 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn); adapter.Fill(ds, sheetName); } catch (System.Data.SqlClient.SqlException ex) { throw ex; } finally { conn.Close(); conn.Dispose(); } } return ds.Tables[sheetName]; }
Web.Config
<configuration> <appSettings> <add key="SNFile" value="C:\SNFile"/> <add key="SNFileWs" value="http://acc-test-01/SNFile"/> </appSettings> </configuration>