如何在 MVC3 中将数据从 Excel 导入到 SQL Server Express 2008

发布于 2024-12-13 20:13:11 字数 2651 浏览 0 评论 0原文

我正在使用 MVC3 和 C# 代码。我的 SQL Server Express 中有一个表,其中包含一些列,并且有一个 Excel 工作表,其中包含相同数量的列、相同的数据类型和名称。

我的要求是我想在 MVC3 应用程序中浏览该 Excel 文件,用户可以在其中选择该文件。我的数据库表和 Excel 工作表中都有一个 RegistrationNo 列。在导入数据库表中的数据之前,应将 Excel 工作表中存在的 RegNo 与数据库表中的 RegNo 进行比较,如果该 RegNo code> 已存在,则不应插入该 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是否存在。

I'm using MVC3 with C# code. I have a table in my SQL Server Express containing some columns, and I have an Excel sheet which has the same number of columns with the same datatypes and names.

My requirement is I want to browse that Excel file in my MVC3 application, where the user can select the file. There is a RegistrationNo column in both my database table as well as in the Excel sheet. Before importing the data in the table of the database the RegNo present in the Excel sheet should be compared with the RegNo in the database table and if that RegNo already exists than no insertion for that RegNO should take place else if that RegNo is not present in the table than the row for that RegNo should be inserted.

Below is my code that I have tried but I'm getting lot of issues with that.

[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();
}   

Here CheckRegNo checks whether the RegNo exists.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

铁憨憨 2024-12-20 20:13:11
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())
 {
     var model = new Student();
     model.Col1=Convert.ToInt32(odr[0]);
     model.Col2 = odr[1].ToString().Trim();
     model.col3 = odr[2].ToString().Trim();
     model.col4 = odr[3].ToString().Trim();
    db.MyTable.AddObject(model);                            
 }
}

这就是我读取 Excel 并从 Excel 保存数据的方式。

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())
 {
     var model = new Student();
     model.Col1=Convert.ToInt32(odr[0]);
     model.Col2 = odr[1].ToString().Trim();
     model.col3 = odr[2].ToString().Trim();
     model.col4 = odr[3].ToString().Trim();
    db.MyTable.AddObject(model);                            
 }
}

This is how im reading the Excel and saving data from Excel.

寂寞笑我太脆弱 2024-12-20 20:13:11

我们也可以使用excel库导入。下面是它的代码。

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            int rCnt;
            int cCnt;
            int rw = 0;
            int cl = 0;
            string str;
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;
            rw = range.Rows.Count;
            cl = range.Columns.Count;

            for (rCnt = 1; rCnt <= rw; rCnt++)
            {
                //Ignore first row as it consists of headers
                if (rCnt > 1)
                {
                    for (cCnt = 1; cCnt <= rw; cCnt++)
                    {
                        str = range.Value2[rCnt, cCnt];
                    }
                }
            }

We can also import using excel library. Below is code for it.

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            int rCnt;
            int cCnt;
            int rw = 0;
            int cl = 0;
            string str;
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;
            rw = range.Rows.Count;
            cl = range.Columns.Count;

            for (rCnt = 1; rCnt <= rw; rCnt++)
            {
                //Ignore first row as it consists of headers
                if (rCnt > 1)
                {
                    for (cCnt = 1; cCnt <= rw; cCnt++)
                    {
                        str = range.Value2[rCnt, cCnt];
                    }
                }
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文