我正在使用MVC3和C#代碼。我在我的SQL Server Express中有一個包含一些列的表,並且我有一個Excel工作表,它具有相同數量的列以及相同的數據類型和名稱。如何將數據從Excel導入到MVC3中的SQL Server Express 2008中
我的要求是我想瀏覽我的MVC3應用程序中的Excel文件,用戶可以在其中選擇文件。我的數據庫表格和Excel表格中都有一個RegistrationNo
列。在數據庫的表中導入數據之前RegNo
存在於Excel工作表應在數據庫表中的RegNo
進行比較,如果該RegNo
比沒有插入已經存在該RegNO
應該採取別的地方如果RegNo
不存在的應該插入表格,比應該插入的那行RegNo
。
下面是我嘗試過的代碼,但我遇到了很多問題。
[HttpPost]
public ActionResult AdmissionUpload()
{
string filePath = null;
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase Infile = Request.Files[inputTagName];
if (Infile.ContentLength > 0 && (Path.GetExtension(Infile.FileName) == ".xls" || Path.GetExtension(Infile.FileName) == ".xlsx" || Path.GetExtension(Infile.FileName) == ".xlsm"))
{
filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(Infile.FileName));
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
Infile.SaveAs(filePath);
//Infile.SaveAs(filePath);
}
if (filePath != null)
{
System.Data.OleDb.OleDbConnection oconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath.ToString() + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";");
oconn.Open();
try
{
if (oconn.State == System.Data.ConnectionState.Closed)
oconn.Open();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
dynamic myTableName = oconn.GetSchema("Tables").Rows[0]["TABLE_NAME"];
OleDbCommand ocmd = new OleDbCommand("select * from [" + myTableName + "]", oconn);
OleDbDataReader odr = ocmd.ExecuteReader();
if (odr.HasRows)
{
while (odr.Read())
{
if (odr[0].ToString().Trim() != "")
{
if (CheckDepartment(odr[0].ToString().Trim()) == false)
{
var model = new DepartmentMaster();
model.DepartmentName = odr[1].ToString().Trim();
db.DepartmentMasters.AddObject(model);
db.SaveChanges();
FLAG = true;
}
}
}
}
}
}
return View();
}
這裏CheckRegNo
檢查RegNo
是否存在。
你可以**更具體**關於**什麼**問題/錯誤是??? –
foreach(在Request.Files中輸入字符串inputTagName) {} 當我調試,看看它的問題是什麼,它只是沒有移動此代碼循環。它檢查文件請求,然後立即返回View()。 –