简体   繁体   中英

C# Error reading Excel file with OleDbDataAdapter

I'm trying to read an ".xlsx" file using an OleDbDataAdapter. Please read until the end of the post before answering. Here is the code I'm using:

    private DataTable ExtractDataFromFile(string fileName)
    {
        DataTable sheetData = new DataTable();
        using (OleDbConnection conn = this.returnConnection(fileName))
        {
            try{
                conn.Open();
                OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [Sheet1$]", conn);
                sheetAdapter.Fill(sheetData);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
        return sheetData;
    }

    private OleDbConnection returnConnection(string fileName)
    {
        return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");
    }

But I'm getting a peculiar error. The Excel files I have to query have been given to me by a client, and I get the following error when I try to open them

External table is not in the expected format

Here is the catch: I've noticed that if I open one of the Excel files and manually save it once and close the file, then I can query the file with my program!

Are you sure, you have create the xlsx file using Microsoft office? This file could be an open xml document, but maybe not created by MS Office, so the MS oledbadapter cannot read it. If you open and save it then it probably converts it to MS version of open xml and then oledbadapter can read it.

You can look into DocumentFormat.OpenXml to read xlsx files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM