【发布时间】:2015-11-06 19:33:10
【问题描述】:
我是 MVC ASP.NET 的新手,我正在尝试从 Excel 文件导入数据并将其加载到数据库中。
已使用与 Excel 文件中的信息匹配的列名创建数据库。当我上传 Excel 文件并单击提交时,我收到错误:
初始化字符串的格式不符合规范
根据调试,故障出在以下行,目前甚至不确定其余代码是否正确:
excelConnection.Open();
查找了类似的错误问题,但答案不起作用。这部分的完整代码:
//Code at Controller and cshtml
public ActionResult Import()
{
return View();
}
public ActionResult ImportExcel()
{
try
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/App_Data/uploads"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = @"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ExampleDB.mdf;Initial Catalog=aspnet-FormulaOne-20151105055609;Integrated Security=True";
//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False, HDR=YES";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Speed],[Average],[Power],[Comment] from [Sheet1$]", excelConnection);
//ERROR OCCURING AT THIS LINE
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "Stats";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace.ToString());
return RedirectToAction("Import");
}
}
}
@using (Html.BeginForm("Importexcel", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
<tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
</table>
}
【问题讨论】:
-
试过了。引发新错误 - “SaveAs 方法配置为需要根路径,并且路径 '@c:\users\name\documents\visual studio 2015\Projects\Example\App_Data\uploads/Book1.xlsx' 没有根。”
标签: c# asp.net asp.net-mvc excel