سؤال

I am using some legacy code to return an Excel worksheet as a Dataset. However, when I iterate over the resulting data set it seems that not all of the cells are there. The Excel sheet that is being read has some merged cells and I am wondering if that is the problem. Here is the code:

private DataSet Get_Spreadsheet_Data(string strFileName, string strSheetName)
{
    DataSet ds = new DataSet();
    string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;";
    OleDbConnection objConn = new OleDbConnection(strConnectionString);
    try
    {
        objConn.Open();
        OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + strSheetName + "$]", objConn);
        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
        objAdapter1.SelectCommand = objCmdSelect;
        objAdapter1.Fill(ds);
    }
    catch (Exception Ex)
    {
        //litOutput.Text = "<span style=\"color:red;\">Exception Occurred pulling data from the spreadsheet.</span><br>Details: " + Ex.Message;
    }
    finally
    {
        objConn.Close();
        objConn.Dispose();
    }
    return ds;
}

Is this code malfunctioning? Any advice is appreciated.

هل كانت مفيدة؟

المحلول

string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;";

needed to read:

string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties="Excel 8.0;HDR=NO;IMEX=1;";

and that did the trick!

نصائح أخرى

Have you tried running the same code with an Excel file that doesn't have the merged files? That is the first thing I would try if I would wonder if merged cells can cause problems filling your dataset...

Edit for clarification: For debugging purposes: use the same Excel file, only make sure you undo the merging of the cells. Even better is to start with an excel file with 3 rows and 3 columns:

Row one: Cell A1 with value 'Foo; Cell B1 'Bar', C1 banana. Row two: Cell A2 Foo1 B2 Bar1 <-- merge those two cells. C2 = Apple. Row three: Cell A3 with value 'Foo2; Cell B3 'Bar2' C3 Orange <-- to check if the next line is read well after using merged cells...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top