简体   繁体   English

C#使用OleDbDataAdapter读取Excel文件时出错

[英]C# Error reading Excel file with OleDbDataAdapter

I'm trying to read an ".xlsx" file using an OleDbDataAdapter. 我正在尝试使用OleDbDataAdapter读取“ .xlsx”文件。 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 我必须查询的Excel文件已由客户端提供给我,当我尝试打开它们时出现以下错误

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! 这里有个要点:我注意到,如果我打开一个Excel文件并手动保存一次并关闭文件,那么我可以使用程序查询该文件!

Are you sure, you have create the xlsx file using Microsoft office? 确定要使用Microsoft Office创建xlsx文件吗? This file could be an open xml document, but maybe not created by MS Office, so the MS oledbadapter cannot read it. 该文件可能是打开的xml文档,但可能不是MS Office创建的,因此MS oledbadapter无法读取它。 If you open and save it then it probably converts it to MS version of open xml and then oledbadapter can read it. 如果您打开并保存它,则它可能会将其转换为打开xml的MS版本,然后oledbadapter可以读取它。

You can look into DocumentFormat.OpenXml to read xlsx files. 您可以查看DocumentFormat.OpenXml以读取xlsx文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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