我想将我导入的excel文件的特定列添加到数据网格视图中。但问题是,当我点击保存时,我收到以下错误:
"无法转换类型为#System ;DBNull'的对象输入 ' System.String'"
我总共有9列,我只想添加3列。这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (dlg.ShowDialog() == DialogResult.OK)
{
label1.Text = dlg.FileName.ToString();
string path = label1.Text;
string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";
OleDbConnection conn1 = new OleDbConnection(conn);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [Sheet1$]", conn1);
DataTable dataSet = new DataTable();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet;
}
}
private void button2_Click(object sender, EventArgs e)
{
using (MySqlConnection conn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand();
MySqlDataReader reader;
MySqlCommand command2 = new MySqlCommand();
//MySqlDataReader reader1;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Boolean Empty = true;
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if ((string)dataGridView1.Rows[i].Cells[j].Value != "")
{
Empty = false;
StrQuery = @"INSERT Ignore INTO course(Code,Course,Major) VALUES ('"
+ dataGridView1.Rows[i].Cells["Course Code"].Value + "','"
+ dataGridView1.Rows[i].Cells["Course"].Value + "','"
+ dataGridView1.Rows[i].Cells["Major"].Value + "')";
cmd.CommandText = StrQuery;
cmd.ExecuteNonQuery();
}
}
if (Empty)
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
}
}
MessageBox.Show("Successfully Added!");
}
}