日期:2014-05-18  浏览次数:20677 次

c# Excel导入 问题求解
private void btnChoose_Click(object sender, EventArgs e)
  {
  this.openFileDialog1.ShowDialog();
  this.txtfilepath.Text = this.openFileDialog1.FileName;
  filePath = this.txtfilepath.Text;
  }

  private void btnLeadin_Click(object sender, EventArgs e)
  {
  if(filePath.Trim()=="")
  {
  MessageBox.Show("请先选取要导入的 Excel表格","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
  return;
  }
  //string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Dir + "\\" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
  string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + filePath + ";Extended Properties='Excel 8.0;IMEX=1;HDR=Yes;'";
  OleDbConnection cnnxls = new OleDbConnection(connect);
  OleDbDataAdapter dbAdapter = new OleDbDataAdapter("select * from [sheet1$]",cnnxls) ;

  DataSet dsTarget = new DataSet();
  dbAdapter.Fill(dsTarget);
   
  this.dataGridView1.DataSource = dsTarget.Tables[0];

  this.dataGridView1.Columns[0].Width = 60;
  this.dataGridView1.Columns[1].Width = 80;
  this.dataGridView1.Columns[2].Width = 60;
  this.dataGridView1.Columns[3].Width = 60;
  }

  private void btnSave_Click(object sender, EventArgs e)
  {
  try
  {
  for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
  {
  No = "";
  name = "";
  tel = "";
  date = "";
  if (this.dataGridView1.Rows[i].Cells[0].Value != null)
  {
  No = this.dataGridView1.Rows[i].Cells[0].Value.ToString();
  }
  if (this.dataGridView1.Rows[i].Cells[1].Value != null)
  {
  name = this.dataGridView1.Rows[i].Cells[1].Value.ToString();
  }
  if (this.dataGridView1.Rows[i].Cells[2].Value != null)
  {
  tel = this.dataGridView1.Rows[i].Cells[2].Value.ToString();
  }
  if (this.dataGridView1.Rows[i].Cells[3].Value != null)
  {
  date = this.dataGridView1.Rows[i].Cells[3].Value.ToString();
  }
  sql = "insert into tb_matchplayer values('" + No + "','" + name + "','" + tel + "','" + date + "')";
  dc.getcom(sql);
  }
  MessageBox.Show("导入数据成功", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

  }
  catch (Exception ex)
  {
  MessageBox.Show("导入数据失败,请检查Excel的格式是否标准", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

  }
  }

在导入时 EXCEL格式正确时,提示导入失败时,却导入成功了;EXCEL