【发布时间】:2015-03-17 16:59:58
【问题描述】:
我想通过 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();
【问题讨论】:
-
请浏览这个有用的帖子,[如何在 C# 中将所有 Excel 工作表导入 DataSet][1] [1]:stackoverflow.com/questions/18006318/…
标签: asp.net-mvc asp.net-mvc-4 excel vba