Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OleDataAdapter Fill Method Returning Empty Rows To Data Table

Here is my code:

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

When this method is called, I don't get an error at all! When I put a watch on the data table (dt), I can see that it is empty. No row headers, and the rows are empty. I know the query is valid to some degree, because the Rows.Count on dt returns the number of rows in the sheet that I am querying.

What could I be doing incorrectly?

Thanks for the help!

EDIT: Here is my Connection String

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

I am putting the file location in place of {0}

like image 758
Dillon Willis Avatar asked Jun 05 '26 03:06

Dillon Willis


1 Answers

Establish a Connection

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;

Accessing Sheets

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();
  • REFERENCE.
like image 136
Khurram Ali Avatar answered Jun 07 '26 22:06

Khurram Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!