OLEDB打开Excel文件的实现方法

话不多说,上代码!

class clsoledb
  {
    OleDbConnection connection;
    public void OpenConnection(string xlsFils)
    {
      if (!File.Exists(xlsFils))
      {
        MessageBox.Show("文件" + xlsFils + "不存在", "提示");
        return;
      }
      string conn = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source =" + xlsFils + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";
      connection = new OleDbConnection(conn);
      try
      {
        connection.Open();
      }
      catch (OleDbException ex)
      {
        if (ex.ErrorCode == -2147467259)
        {
          connection.ConnectionString = "Provider = Microsoft.Ace.OLEDB.12.0;Data Source =" + xlsFils + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1;'";
          connection.Open();
        }
      }
    }

    public DataTable Select()
    {
      DataTable dt = new DataTable();
      string Sql = "select * from [$A1:R65536]";
      OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, connection);
      mycommand.Fill(dt);

      if (dt.Rows.Count > 0)
      {
        DataRow dr = dt.Rows[0];
        for (int col = 0; col < dt.Columns.Count; col++)
        {
          dt.Columns[col].ColumnName = dr[col].ToString();
        }
        dt.Rows[0].Delete();
        dt.AcceptChanges();
      }
      return dt;
    }

  }

以上这篇OLEDB打开Excel文件的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。