【发布时间】:2014-03-18 21:33:55
【问题描述】:
当我调用函数上传 Excel 时,我正在使用 .xls 作为文件扩展名从 Excel 工作表中导入学生记录中的数据
public ActionResult Importexcel()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), 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)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-UserInfo-20140318063343.mdf;Initial Catalog=aspnet-UserInfo-20140318063343;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";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Id],[Name],[StudentId] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "StudentRecords";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
}
我收到以下错误
从“System.String”到“System.Guid”的无效转换。
我的模型在下面,我无法更改 Guid,因为这是我的必要需求
public class StudentRecord
{
public long Id { get; set; }
public string Name { get; set; }
public Guid StudentId { get; set; }
}
【问题讨论】:
-
不确定对工作表的 ole 访问是否会具有此功能,但 new OleDbCommand("Select [Id],[Name],Cast(StudentId as UniqueIdentifier) as StudentID .." 可能会完成这项工作
标签: mysql sql asp.net-mvc-4 sqlbulkcopy