将多个Excel工作表导入SQL Server表

时间:2018-09-26 01:19:15

标签: c# sql-server excel asp.net-mvc

我大约有20个文件,所有文件都超过20张。我需要将所有工作表中的特定数据导入表(与表相同的列)。我的代码只能导入一张纸。如何导入多张纸?以及如何从Excel导入特定的单元格?我读了很多问题,但是我什么都做不了,而且大多数都是旧的

数据库是SQL Server。我希望你能帮助我。我是新手。

public ActionResult Index()
{
   return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
        string filePath = string.Empty;

        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);

            string conString = string.Empty;

            switch (extension)
            {
                case ".xls": //Excel 97-03.
                    conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                    break;

                case ".xlsx": //Excel 07 and above.
                    conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                    break;
            }

            DataTable dt = new DataTable();
            conString = string.Format(conString, filePath);

            using (OleDbConnection connExcel = new OleDbConnection(conString))
            {
                using (OleDbCommand cmdExcel = new OleDbCommand())
                {
                    using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                    {
                        cmdExcel.Connection = connExcel;

                        //Get the name of First Sheet.
                        connExcel.Open();
                        DataTable dtExcelSchema;
                        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        connExcel.Close();

                        //Read Data from First Sheet.
                        connExcel.Open();
                        cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
                        odaExcel.SelectCommand = cmdExcel;
                        odaExcel.Fill(dt);
                        connExcel.Close();
                    }
                }
            }

            conString = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.Table_1";

                    //[OPTIONAL]: Map the Excel columns with that of the database table
                    sqlBulkCopy.ColumnMappings.Add("Rut", "Rut");
                    sqlBulkCopy.ColumnMappings.Add("Nombres", "Nombres");
                    sqlBulkCopy.ColumnMappings.Add("Malla", "Malla");

                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                }
            }
        }

        return View();
    }
}

1 个答案:

答案 0 :(得分:0)

我不知道您将如何使SQL Server做到这一点,而且如果您可以使C#做到这一点,可能会更加困难。我的意思是,您有这样的选择...

SELECT * INTO XLImport5 FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\xltest.xls', 'SELECT * FROM [Customers$]')

这将从名为“ Customers”的工作表中导入所有内容(您需要在其中保留该$字符)。希望所有这些Excel文件之间都有某种一致的模式,但我只是在猜测。无论如何,如果我是您,我将通过下面的链接安装AddIn。遵循GIU并在Excel中聚合数据,因为在该环境中操作几乎可以肯定会容易得多。然后...将其从Excel发送到SQL Server。

https://www.rondebruin.nl/win/addins/rdbmerge.htm

enter image description here