cshap将execl表格写入sqlserver
时间: 2024-01-16 16:04:46 浏览: 97
您可以使用以下步骤将Excel表格写入SQL Server:
1. 在Visual Studio中创建一个C#项目。
2. 添加一个连接到SQL Server数据库的连接字符串。
3. 使用OleDbConnection和OleDbCommand类来打开Excel文件并读取数据。
4. 使用SqlBulkCopy类将数据从Excel文件复制到SQL Server表中。
以下是一个示例代码:
```
using System.Data.OleDb;
using System.Data.SqlClient;
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourExcelFile.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string sqlConnectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True;";
// Open the Excel file and read data
using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
{
excelConnection.Open();
OleDbCommand excelCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", excelConnection);
using (OleDbDataReader excelReader = excelCommand.ExecuteReader())
{
// Create a new SQL Server connection and open it
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
{
sqlConnection.Open();
// Create a new SQL Server table to hold the data from the Excel file
using (SqlCommand sqlCommand = new SqlCommand("CREATE TABLE #TempTable (Column1 INT, Column2 VARCHAR(50))", sqlConnection))
{
sqlCommand.ExecuteNonQuery();
}
// Use SqlBulkCopy to copy data from the Excel file to the SQL Server table
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnection))
{
bulkCopy.DestinationTableName = "#TempTable";
bulkCopy.WriteToServer(excelReader);
}
// Insert data from the temporary table into the target table
using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO YourTableName (Column1, Column2) SELECT Column1, Column2 FROM #TempTable", sqlConnection))
{
sqlCommand.ExecuteNonQuery();
}
// Drop the temporary table
using (SqlCommand sqlCommand = new SqlCommand("DROP TABLE #TempTable", sqlConnection))
{
sqlCommand.ExecuteNonQuery();
}
}
}
}
```
阅读全文
相关推荐

















