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

OleDbDataAdapter 读取Excel数据时出现错误 OleDbException至少一个参数没有被指定值
小弟用C#Winform做了个小系统,要从Excel表格中导入数据,问题就出在导入数据上,从网上搜索的代码,使用oledb来读取的,代码如下:
class excel2Sql
  {
  SqlHander sqlconn = new SqlHander();

  public void SelectFile(string tableName)
  {
  //测试,将excel中的sheet1导入到sqlserver中  
  OpenFileDialog fd = new OpenFileDialog();
  fd.InitialDirectory = "C:\\";
  fd.Filter = "Excel files (*.xls)|*.xls";
  if (fd.ShowDialog() == DialogResult.OK)
  {
  // TransferData(fd.FileName, "sheet1", tableName);
  TransferData(fd.FileName, tableName);

  }
  }
  //public void TransferData(string excelFile,string sheetName, string tableName)
  public void TransferData(string excelFile, string tableName)
  {  

  DataSet ds = new DataSet();
  try
  {
  //获取全部数据
  string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
  OleDbConnection conn = new OleDbConnection(strConn);
  conn.Open();
  string strExcel = "";

  //获取excel表  
  DataTable dataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

  //获取sheet名,其中[0][1]…[N]: 按名称排列的表单元素  
  string sheetName = dataTable.Rows[0][2].ToString().Trim();
  sheetName = "[" + sheetName.Replace("'", "") + "]";  

  OleDbDataAdapter myCommand = null;
   
  // strExcel = string.Format("select * from {0}", sheetName);
  strExcel = string.Format("select 进/出口,提单号,重20,吉20,重40,吉40,重45,吉45,截关时间,客户名称,重/吉,货柜总重,危品类别,是否税品,是否冷冻柜,免柜期,装柜点,卸柜点 from {0}", sheetName);
问题出在这:当使用strExcel = string.Format("select 进/出口....这个语句时,就出现上述错误,当使用strExcel = string.Format("select * from {0}", sheetName);时没有错误提示,但是这要求Excel表格的第一列要添加一列无关的列,否则导入的数据将会出现错位的情况,这一列对用户来说是完全没有必要的,请问 如何在去掉这一列的情况下还能不错位的导入数据?
   
  myCommand = new OleDbDataAdapter(strExcel, strConn);
  myCommand.Fill(ds, sheetName);



  //目标表有无数据都删除
  sqlconn.ExecuteSQL("truncate table " + tableName);


  //用bcp导入数据
  using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy("server=localhost;uid=sa;pwd=sa123;database=ShipArrange"))
  {
  bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
  bcp.BatchSize = 100;//每次传输的行数
  bcp.NotifyAfter = 100;//进度提示的行数
  bcp.DestinationTableName = tableName;//目标表
  bcp.WriteToServer(ds.Tables[0]);
  }
  MessageBox.Show("导入成功!", "提示信息:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  }
  catch (Exception ex)
  {
  MessageBox.Show("对不起,文件导入失败!请严格按照模板要求!", "