@Sue_8827 , based on my test, I reproduced your problem. You could try to add code MultipleActiveResultSets=True;
to the sqlerver connectionstring if you just want to solve the problem you mentioned.
According to your code, I find that you are getting the sheetname and the filepath from the excel. I prefer that you use the insert statement to add the data from the datatable to the database instead of using SqlBulkCopy to do it. Because the filepath is not coming from the datatable.
Here is a code example you could refer to.
static void Main(string[] args)
{
string FilePath = "D:\\Example.xlsx";
string TableName = "Example";
string SchemaName = "dbo";
//Declare and initilize variables
string fileFullPath = "";
SqlConnection myADONETConnection = new SqlConnection("Connstr; MultipleActiveResultSets=True;");
myADONETConnection.Open();
fileFullPath = FilePath;
string filename = "D:\\Example.xlsx";
filename = FilePath;
//Create Excel Connection
string ConStr;
string HDR;
HDR = "YES";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
//Only read data from provided SheetNumber
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
string sql = string.Format("insert into {0} (FilePath,SheetName) values(@FilePath,@SheetName)", SchemaName + "." + TableName);
SqlCommand cmd = new SqlCommand(sql, myADONETConnection);
cmd.Parameters.AddWithValue("@FilePath", FilePath);
cmd.Parameters.AddWithValue("@SheetName", sheetname);
cmd.ExecuteNonQuery();
}
}
}
Result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.