Ext.Net导入Excel

根据上传的Excel文件保存在指定目录:

 1 protected void btnUpload_DirectClick(object sender, DirectEventArgs e)
 2         {
 3             string fileName = this.fileUploader.FileName;
 4             string extension = Path.GetExtension(fileName).ToUpper();
 5             byte[] content = this.fileUploader.FileBytes;
 6             if (extension == ".XLS"||extension==".XLSX")
 7             {
 8                 if (!Directory.Exists(Server.MapPath("~/FileUpload/")))
 9                 {
10                     Directory.CreateDirectory(Server.MapPath("~/FileUpload/"));
11                 }
12                 try
13                 {
14                     string filePath = Server.MapPath("~/FileUpload/") + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
15                     fileUploader.PostedFile.SaveAs(filePath);
16                     DataSet ds = ExcelHelper.LoadDataFromExcel(filePath);
17                     DataTable tbData = ds.Tables[0];
18                     for (int i = 0; i < tbData.Columns.Count; i++)
19                     {
20                         tbData.Columns[i].ColumnName = ExcelHelper.GetColumnName(tbData.Columns[i].ColumnName);
21                     }
22                     //storeUser.DataSource = ds.Tables[0];
23                     //storeUser.DataBind();
24                 }
25                 catch (Exception ex)
26                 {
27                     throw ex;
28                 }
29             }
30             else
31             {
32                 X.MessageBox.Alert("提示", "文件格式不正确");
33             }
34         }
View Code

把Excel中的数据读取到DataSet中:

 1  /// <summary>
 2         /// 加载Excel数据
 3         /// </summary>
 4         /// <param name="filePath">文件路径</param>
 5         /// <returns>数据源</returns>
 6         public static DataSet LoadDataFromExcel(string filePath)
 7         {
 8             string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
 9             OleDbConnection conn = new OleDbConnection(connectionString);
10             conn.Open();
11             String sql = "SELECT * FROM  [Sheet1$]";
12 
13             OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, conn);
14             DataSet OleDsExcel = new DataSet();
15             OleDaExcel.Fill(OleDsExcel, "Sheet1");
16             conn.Close();
17 
18             return OleDsExcel;
19         }
View Code
原文地址:https://www.cnblogs.com/hongyan5682/p/5076292.html