gpt4 book ai didi

c# - 使用 C# 解析 XLS 文件时出现问题

转载 作者:行者123 更新时间:2023-11-30 14:05:25 25 4
gpt4 key购买 nike

好吧,让我们看看我是否能让这说得通。

我编写了一个程序来解析 Excel 文件,它工作正常。我使用以下方法进入文件:

string FileToConvert = Server.MapPath(".") + "\\App_Data\\CP-ARFJN-FLAG.XLS";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileToConvert + ";Extended Properties=Excel 8.0;";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
//this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [CP-ARFJN-FLAG$]", connection);

这很好用。但是当我在实际文件上尝试它时(它是由另一个程序提供给我的)我得到这个错误:

System.Data.OleDb.OleDbException: External table is not in the expected format. at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at wetglobe.Page_Load(Object sender, EventArgs e)

但是,我认为这就是问题所在。如果我获取该文件,并将其保存在我的本地 Excel 中,首先我会看到这个弹出窗口:

CP-ARFJN-FLAG.XLS may contain features that are not compatible with Text (Tab delimited). Do you want to keep the workbook in this format?

  • To Keep this format, which leaves out any incompatible features, click Yes.
  • To preserve the features, click No. Ten save a copy in the latest Excel format.
  • To see what might be lost, click Help.

如果我单击“否”,然后将其另存为当前的 Excel 格式,程序将正常运行。

所以我假设这是以某种疯狂的旧 Excel 格式保存的?

我想我的问题是:

  • 如何判断 Excel 版本保存了吗?
  • 我怎样才能在当前的情况下解析它状态?
  • - 或者- 我可以通过编程将其保存为较新版本吗?

我希望这很清楚...谢谢。

最佳答案

听起来您的第三方应用程序生成的 XLS 文件可能不是真正的 Excel 格式 - 它实际上可能是一个制表符分隔的文本文件,扩展名为 .xls。

试着用文本编辑器打开它看看。

如果它是制表符分隔的,您可以放弃 OleDB 适配器并将其作为标准文本文件打开/解析。

关于c# - 使用 C# 解析 XLS 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com