如何在mvc中导入Excel多个工作表

时间:2014-10-15 05:09:54

标签: asp.net-mvc excel asp.net-mvc-4 excel-vba vba

我想通过excel表在mvc5中注册用户,所以我在一个excel文件中有多个工作表。所以我无法获得如何将多个工作表导入多个表以便注册用户及其他信息。

     public ActionResult ImportUser()
      {
        if (Request.Files["FileUpload1"].ContentLength > 0)
         {
          string FileName = System.IO.Path.GetFileName(Request.Files["FileUpload1"].FileName);

           string fileExtension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
              if (fileExtension == "" || fileExtension == ".xlsx")
                 {

             string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
             Request.Files["FileUpload1"].SaveAs(path1);
             string sqlConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1+ ";Extended Properties=Excel 12.0;Persist Security Info=False";
        //Create Connection to Excel work book and add oledb namespace
            OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
            excelConnection.Open();
            DataTable dt = new DataTable();
            dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
             if (dt == null)
               {
                  return null;
               }
           String[] excelSheets = new String[dt.Rows.Count];
           int t = 0;
              //excel data saves in temp file here.
           foreach (DataRow row in dt.Rows)
            {
              excelSheets[t] = row["TABLE_NAME"].ToString();
              t++;
            }
             OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
             DataSet ds = new DataSet();
             string query = string.Format("Select * from [{0}]", excelSheets[0]);
             using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
              {
                dataAdapter.Fill(ds);
               }                  
               for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
               {                        

           SqlConnection sqlc = new SqlConnection();
           sqlc.ConnectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Planetskool-20140309125429.mdf;Initial Catalog=aspnet-Planetskool-20140309125429;Integrated Security=True";

 SqlCommand cmd2 = new SqlCommand("INSERT INTO IdentityUser (Id,UserName,PasswordHash,SecurityStamp)  VALUES(@Id,@UserName,@PasswordHash,@SecurityStamp)", sqlc);//@OB_ID is indentity primary key

cmd2.Parameters.Add("@Id", SqlDbType.VarChar).Value = (ds.Tables[0].Rows[j]["Id"]).ToString();
cmd2.Parameters.Add("@UserName", SqlDbType.VarChar).Value = (ds.Tables[0].Rows[j]["UserName"]).ToString();
cmd2.Parameters.Add("@PasswordHash", SqlDbType.VarChar).Value = (ds.Tables[0].Rows[j]["PasswordHash"]).ToString();
 cmd2.Parameters.Add("@SecurityStamp", SqlDbType.VarChar).Value = (ds.Tables[0].Rows[j]["SecurityStamp"]).ToString();
                  sqlc.Open();
                  cmd2.ExecuteNonQuery();
                  sqlc.Close();

1 个答案:

答案 0 :(得分:0)

编写如下代码可能对您有帮助

    public void ImportXLX()
        {


                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

                    Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(@"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing);

                    int workSheetCounts = wb.Worksheets.Count;

                    for (int sheetCounter = 1; sheetCounter <= workSheetCounts; sheetCounter++)
                    {
                        Microsoft.Office.Interop.Excel.Worksheet workSheet = wb.Sheets[sheetCounter];
}
}