我在窗口应用程序的数据网格视图中导入了一个csv文件。它有40列数据,超过100条记录。现在我想要的是将网格视图数据保存到数据库。 我尝试过bulkinsert,但它给出了错误:无法访问目标表 我不确定如何在这种情况下创建表。我的意思是我需要定义所有40列吗?如果每次导入csv文件时,列名都不同?
以下是我一直在尝试的代码:
string rowValue="";
string[] cellValue;
DataTable dt = new DataTable();
if (System.IO.File.Exists(csvPath.Text))
{
System.IO.StreamReader streamReader = new StreamReader(csvPath.Text);
// Reading header
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i < cellValue.Count(); i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i];
dataGridView1.Columns.Add(column);
}
// Reading content
while (streamReader.Peek() != -1)
{
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
dataGridView1.Rows.Add(cellValue);
}
streamReader.Close();
}
else
{
MessageBox.Show("Please Select a File!");
}
dataGridView1.DataSource = dt;
保存到数据库表:
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\tushar\\dbLws.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
if (string.IsNullOrEmpty(tbName.Text.Trim()))
{
MessageBox.Show("Please supply Table Name");
}
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.Default);
sqlBulkCopy.DestinationTableName = tbName.Text.Trim();
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
sqlBulkCopy.ColumnMappings.Add(dataGridView1.Columns[i].Name, dataGridView1.Columns[i].Name);
}
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
sqlBulkCopy.WriteToServer(dt);
sqlBulkCopy.Close();
MessageBox.Show("Saved successfully");
con.Close();
}