我在我的窗口应用程序的数据网格视图中导入了一个 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();
}