我想将excel数据插入sql,但是excel列名经常更改。
下面是我为excel批量上传编写的代码
string excelConnectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", path);
//// Create Connection to Excel Workbook
{
string destablename1 = string.Empty;
destablename1 = "[admin.AttendanceData]";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(excelConnectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [Attendance$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
var dacObj = new DAC();
String strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnection))
{
bulkCopy.ColumnMappings.Add("Emp ID", "Citrix_ID");
bulkCopy.ColumnMappings.Add("Full Name", "Full_Name");
bulkCopy.ColumnMappings.Add("Band", "Band");
bulkCopy.ColumnMappings.Add("Cigna DOJ", "Cigna_DOJ");
bulkCopy.DestinationTableName = destablename1;
dacObj.OpenConnection();
bulkCopy.WriteToServer(Data);
dacObj.CloseConnection();
}
}n
如何从Excel向SQL添加动态列名?
excel工作表数据的示例图片
此后,信诺(Cigna)DOJ列将每月更改一次。