简体   繁体   English

用代码覆盖Excel文件

[英]Overwrite excel file with code

I'm using visual studio 2008 to create a console application on c#. 我正在使用Visual Studio 2008在c#上创建控制台应用程序。

The application "reads" an excel file 97-2003 (.XLS). 该应用程序“读取” Excel文件97-2003(.XLS)。

I'm using jet to read the file: 我正在使用jet来读取文件:

OleDbConnection oConn = new OleDbConnection();
   oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + file_path  + " ;Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\";";    

But when running the program I get error "External table is not in the expected format." 但是,在运行程序时,出现错误“外部表的格式不正确”。

I have tried reading the excel file with the NPOI library and i got error: 我尝试使用NPOI库读取excel文件,但出现错误:

Message = "Invalid header signature; read 0x0010000000060809, expected 0xE11AB1A1E011CFD0" 消息=“无效的标头签名;读取0x0010000000060809,预期0xE11AB1A1E011CFD0”

So, it's like the file is invalid in some way. 因此,就好像文件在某种程度上是无效的。

If, through Windows, I open the excel file on Office Excel, then save it with the same and same extension .xls overwriting it , and after that I run the console application, then the application runs fine with no error. 如果通过Windows在Office Excel上打开excel文件,然后使用相同和相同的扩展名.xls进行保存,并覆盖它,然后运行控制台应用程序,则该应用程序可以正常运行且没有错误。

So, what I would like to do is: with c# code, open the file and save it and overwrite it, so the application could read the file successfully. 因此,我想做的是:使用C#代码打开文件并保存并覆盖它,以便应用程序可以成功读取文件。

I guess I could open the file like this: 我想我可以这样打开文件:

File.OpenWrite(file_path);

But how could I overwrite the file? 但是,如何覆盖文件?

You don't need to open and rewrite it, as far as I can see. 据我所知,您无需打开并重写它。 Your connection string is wrong. 您的连接字符串错误。 You're not saying anywhere it's an Excel file, so by default it's looking for an Access database instead (and not finding one). 您并不是在说它是Excel文件的任何地方,因此默认情况下它是在查找Access数据库(而不是查找数据库)。

Try this instead: 尝试以下方法:

Provider=Microsoft.Jet.OLEDB.4.0; data source="YourFileName.xls"; Extended Properties=Excel 8.0;

For other types of connections, see ConnectionStrings 有关其他类型的连接,请参见ConnectionStrings

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

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