0
**導入Excel文件的DataGridView在C#中,一些缺少列
我想導入Excel中的DataGridView並保存到數據庫中,但所有的第一 我得到在列的一些空白,儘管數據它有數據。
數據顯示在Excel文件中,如圖所示,我想將這個數據 導入到我的DataGridView並將其保存到我的數據庫名稱Records.SDF。
**
private void importFromExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
try
{
string filePath = openFileDialog1.FileName;
string extension = Path.GetExtension(filePath);
string conStr;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
conStr = Excel03ConString; //string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07
string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filePath +
";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';";
conStr = Excel07ConString;
break;
}
String name = "Sheet1";
OleDbConnection con = new OleDbConnection(conStr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
RecordsDataGridView.DataSource = data;
DialogResult result = MessageBox.Show("Are you sure you want to Save the Recreations?", "Save Format",
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (result == DialogResult.Yes) { SaveData(); }
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Exception Occured"); }
}
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
@"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = @"Insert Into ChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
}
不知道爲什麼我得到的第2,第4和第6列空白數據。
我首先要做的就是對其進行調試和DataTable'已經充滿'後檢查data'的'值。 –
數據填充完成後會出現斷點? – Patrick
如果我們可以通過SO網站連接到進程,那麼我們會,但不幸的是,你將不得不調試它。 –