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

时间:2015-07-29 13:08:55

标签: c# excel oledbcommand

这是我的代码:

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;
    }

调用此方法时,我根本不会收到错误!当我把手表放在数据表(dt)上时,我可以看到它是空的。没有行标题,行是空的。我知道查询在某种程度上是有效的,因为dt上的Rows.Count返回我正在查询的工作表中的行数。

我可能做错了什么?

感谢您的帮助!

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

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

我将文件位置放在{0}

的位置

3 个答案:

答案 0 :(得分:1)

建立连接

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();

答案 1 :(得分:0)

点击此链接

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

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

答案 2 :(得分:0)

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

  • 填充(数据集)
  • 填写(DataTable,IDataReader)
  • 填充(DataTable [],IDataReader,Int32,Int32)
  • 填充(DataSet,String,IDataReader,Int32,Int32)

单个DataTable参数没有方法。

在您的情况下,您可以使用Fill(DataSet)方法并返回.Tables [0]或.Tables [&#34; TableName&#34;];

查看以下代码:

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];
}