OleDataAdapter 填充方法将空行返回到数据 Table

OleDataAdapter Fill Method Returning Empty Rows To Data Table

这是我的代码:

public static DataTable GetDataFromSpreadsheet(OleDbConnection conn)
    {
        DataTable dt = new DataTable();
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
        conn.Open();
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        da.Fill(dt);
        conn.Close();
        return dt;
    }

调用此方法时,我完全没有收到错误!当我观察数据 table (dt) 时,我可以看到它是空的。没有行 headers,行为空。我知道查询在某种程度上是有效的,因为 dt returns 上的 Rows.Count 是我正在查询的 sheet 中的行数。

我哪里做错了?

感谢您的帮助!

编辑:这是我的连接字符串

<add name="EXCEL" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
           Data Source={0};
           Extended Properties='Excel 8.0;
           HDR=Yes; IMEX=1;'" />

我将文件位置替换为 {0}

关注这个link

https://www.connectionstrings.com/excel/

尝试在连接字符串中设置 IMEX=1HDR=YES

建立连接

String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=Book1.xls;"
+ "Extended Properties='Excel 8.0;HDR=Yes'";

OleDbConnection connExcel = new OleDbConnection(strExcelConn);
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;

访问工作表

connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close(); 
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
da.SelectCommand = cmdExcel;
da.Fill(ds);
connExcel.Close();

DataAdapter.Fill 方法重载列表如下:

  • 填充(数据集)
  • 填充(数据表,IDataReader)
  • Fill(DataTable[], IDataReader, Int32, Int32)
  • 填充(数据集、字符串、IDataReader、Int32、Int32)

没有单个 DataTable 参数的方法。

在您的情况下,您可以使用 Fill(DataSet) 方法和 return .Tables[0] 或 .Tables["TableName"];

看看下面的代码:

public static DataTable GetDataFromSpreadsheet(OleDbConnection conn)
{
    DataSet ds = new DataSet();
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
    conn.Open();
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    da.Fill(ds);
    conn.Close();
    return ds.Tables[0];
}