首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c# Excel导入 有关问题求解

2012-04-04 
c# Excel导入 问题求解private void btnChoose_Click(object sender, EventArgs e){this.openFileDialog1.

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格式不正确时,提示导入失败时,不能导入。不知是什么原因,求高手解答!

------解决方案--------------------


添加断点,调试,是那句出错的

[解决办法]
for循环里有一条错了吧,debug确定哪一条
另外,拼sql很容易出问题,用sql参数

热点排行