Search code examples
c#oledbxlsoledbconnectionoledbdataadapter

How can I safely convert an XLS sheet to an XML file without knowing the XLS file's sheet name?


I adapated code I found here to convert XLS to XML like so:

try
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.DataSet ds;
    System.Data.OleDb.OleDbDataAdapter MyCommand;
    String fullFilePath = @"C:\worldSeries2014\baltimoreOrioles.xls";
    MyConnection = new 
   System.Data.OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0;Data 
   Source='{0}';Extended Properties=Excel 8.0;", fullFilePath));
    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet0$]", 
      MyConnection);
    MyCommand.TableMappings.Add("Table", "Product"); // I don't know what this does
    ds = new System.Data.DataSet();
    MyCommand.Fill(ds);
    MyConnection.Close();
    ds.WriteXml(@"C:\MiscellaneousJones\os.xml");
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
} 

This works (the xml file is created, with the data from the first sheet on the xls file), as long as the .xls file being loaded has a sheet named "Sheet0"

If I use this line instead (which is what the sample code I started with has):

MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);

...I get, "Sheet1$ is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long"

The dollar sign is apparently necessary, as if I use this:

MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet0]", MyConnection);

...I get, "The Microsoft Jet database engine could not find the object 'Sheet0'"

So, can I rely on "Sheet0" always being the name of the sheet to convert? I'm fairly certain I can't, so how can I use "sheet 0" (the first one) on each occasion, regardless of its name? Alternatively, is there a way to programmatically determine the sheet name and use that?


Solution

  • Using TableSchema you can extract the Worksheet names using OleDb.

    dtSchema = conObj.GetOleDbSchemaTable( OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });