我有一个带有多个选项卡的 Excel sheet,需要使用 C# 将此数据插入 SQL 服务器

I have one Excel sheet with multiple tabs, need to insert this data into SQL Server using C#

我有一个 Excel 文件,其中包含多个 sheet。每个 sheet 名称都与 SQL 服务器中的 table 名称相同。我需要将这些 Excel sheet 的数据插入到数据库中相应的 table 中。

SQL 服务器数据库中有 13 个选项卡和 13 个 table。

我可以使用下面的代码将一个 sheet 的数据插入一个 table。

String strConnection = "Data Source=.;Initial Catalog=<>;Integrated Security=True";

String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);

// Create Connection to Excel work book 
OleDbConnection conn = new OleDbConnection(excelConnString);

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;

OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();

conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtSheet.Rows[0]["table_name"].ToString();
cmd.CommandText = "select * from [" + sheetName + "]";
da.SelectCommand = cmd;
da.Fill(dt);

using (OleDbDataReader dReader = cmd.ExecuteReader())
{
    using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
    {
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "TABLE NAME IN SQL";
        sqlBulk.WriteToServer(dReader);

        conn.Close();
    }
}

如何从所有 sheet 中插入数据?

下面应该这样做 - 你只需要遍历 tables table 中的每一行:

    ...
    DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    // iterate each sheet
    foreach (System.Data.DataRow sheet in dtSheet.Rows)
    {
        string sheetName = sheet["table_name"].ToString();
        cmd.CommandText = "select * from [" + sheetName + "]";
        da.SelectCommand = cmd;
        da.Fill(dt);

        using (OleDbDataReader dReader = cmd.ExecuteReader())
        {
            using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
            {
                // Give your Destination table name.  Table name is sheet name minus any $
                sqlBulk.DestinationTableName = sheetName.Replace("$", "");
                sqlBulk.WriteToServer(dReader);

                conn.Close();
            }
        }
    }
}