---
title: "C# OLEDB 读取Excel2003、Excel2007的内容到Table"
author: "wlhx"
date: "2013-11-06T15:10:05Z"
tags: ["C#", "Excel"]
categories: ["编程语言"]
slug: "c-oledb-excel2003-excel2007-table"
draft: false
lastmod: "2013-11-06T15:13:02Z"
id: 1972082
url: "https://wlhx.iteye.com/blog/1972082"
---

OLEDB 读取Excel2003、Excel2007内容为Table
```C#

private DataTable GetData(string Path, string exceltype)
{
   try
   {
     string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
       if (exceltype == ".xlsx")
       {
          strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=" + "\"" + "Excel 12.0;HDR=Yes;IMEX=1" + "\"";
        }
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        //得到所有sheet的名称
         DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
        string strExcel = "";
        OleDbDataAdapter myCommand = null;
        strExcel = "select * from [" + dtsheetname.rows[0]["table_name"].ToString() + "]";
         myCommand = new OleDbDataAdapter(strExcel, strConn);
         DataTable dt = new DataTable();
         myCommand.Fill(dt);
         conn.Close();
         return dt;
   }
   catch (Exception ex)
   {
       return new DataTable();
   }
}
//注意：如果读取Excel2007的话请下载http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe文件并安装
```