如何在 C++ 中将数据读/写到 excel 2007 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1727361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:01:38  来源:igfitidea点击:

How to read/write data into excel 2007 in c++?

c++excel-2007visual-c++-6

提问by yesraaj

How to read/write data into excel 2007 in c++?

如何在 C++ 中将数据读/写到 excel 2007 中?

采纳答案by Oleg

Excel provides COM interface which you can use from your C++ application.

Excel 提供了可以在 C++ 应用程序中使用的 COM 接口。

I have experience with Excel 2003 only but I think for excel 2007 it will also work.

我只有 Excel 2003 的经验,但我认为对于 excel 2007 也可以使用。

This can be done e.g. with #import or in the way described in this article: http://support.microsoft.com/kb/216686

这可以通过 #import 或本文中描述的方式完成:http: //support.microsoft.com/kb/216686

回答by wisty

There is a python solution (using COM dispatch) here: http://snippets.dzone.com/posts/show/2036

这里有一个 python 解决方案(使用 COM 调度):http: //snippets.dzone.com/posts/show/2036

It's not C++, but the COM interface should be the same no matter which language you use, right?

它不是C++,但是无论您使用哪种语言,COM 接口都应该是相同的,对吧?

You wouldn't need to port everything. Just __init__, set_range, get_value, set_value, save(or save_as), close, and quit. You might also need to dispose of garbage (as python has automatic gc).

您不需要移植所有内容。只是__init__, set_range, get_value, set_value, save(or save_as), close, 和quit。您可能还需要处理垃圾(因为 python 具有自动 gc)。

Or you could just port (and modify) the following code (which I haven't tested, as I don't have excel anymore - you should probably check it by downloading python and pythonwin):

或者你可以移植(并修改)以下代码(我没有测试过,因为我不再有 excel - 你应该通过下载 python 和 pythonwin 来检查它):

from win32com.client import Dispatch
app = Dispatch("Excel.Application")
app.Visible = True # spooky - watch the app run on your desktop!
app.Workbooks.Open("C:\book.xls")

range = app.ActiveWorkbook.Sheets(1).Range("a1") 
print 'The range was:'
print range.Value

range.Value = 42

print 'The value is now 42'  

app.ActiveWorkbook.Save()
app.ActiveWorkbook.SaveAs("C:\excel2.xls")

app.ActiveWorkbook.Close()
app.Quit()

# any gc to do?

回答by Redax

Excel 2007 files are simply zip files. Try to rename .xlsx to .zip: you can extract files and folders. With a text editor you can view that they are all XML files.

Excel 2007 文件只是 zip 文件。尝试将 .xlsx 重命名为 .zip:您可以解压缩文件和文件夹。使用文本编辑器可以查看它们都是 XML 文件。

So the solution:

所以解决办法:

  1. use a common class to unzip your xlsx
  2. use an xml parser to grab you data
  3. if you have modified somethig, re-zip all
  1. 使用通用类解压缩您的 xlsx
  2. 使用 xml 解析器来获取数据
  3. 如果您修改了某些内容,请重新压缩所有内容

No COM object required. Depending on your c++ compiler you can easyly find the required sources.

不需要 COM 对象。根据您的 C++ 编译器,您可以轻松找到所需的源代码。

回答by AndyUK

There are three main things you need to do.

您需要做三件主要的事情。

1) Ensure pre-requisite files are installed and locatable.

1) 确保先决条件文件已安装并可定位。

Blindingly obvious I know, but make sure you have a suitable version of Excel installed, so that you can locate the required Microsoft libraries (and their locations). namely MSO.DLL, VBE6EXT.OLB and EXCEL.EXE

我知道这是显而易见的,但请确保您安装了合适版本的 Excel,以便您可以找到所需的 Microsoft 库(及其位置)。即 MSO.DLL、VBE6EXT.OLB 和 EXCEL.EXE

2) Set up the Microsoft libraries.

2) 设置 Microsoft 库。

In your C++ code, let's say you start with a simple console application, be sure to include the import libraries in any C++ application that interfaces with Excel. In my example I use:

在您的 C++ 代码中,假设您从一个简单的控制台应用程序开始,确保在任何与 Excel 交互的 C++ 应用程序中包含导入库。在我的例子中,我使用:

#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE11\MSO.DLL" \
rename( "RGB", "MSORGB" )

using namespace Office;  

#import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\VBE6EXT.OLB"  

using namespace VBIDE;  

#import "C:\Program Files (x86)\Microsoft Office\OFFICE11\EXCEL.EXE" \  
    rename( "DialogBox", "ExcelDialogBox" ) \  
    rename( "RGB", "ExcelRGB" ) \  
    rename( "CopyFile", "ExcelCopyFile" ) \  
    rename( "ReplaceText", "ExcelReplaceText" ) \  
    exclude( "IFont", "IPicture" ) no_dual_interfaces 

3) Use the Excel Object Model in your C++ code

3) 在 C++ 代码中使用 Excel 对象模型

For example, to declare an Excel Application Object pointer for reading / writing an Excel Workbook:

例如,要声明用于读取/写入 Excel 工作簿的 Excel 应用程序对象指针:

Excel::_ApplicationPtr pXL;  
pXL->Workbooks->Open( L"C:\dump\book.xls" );

And to access and manipulate the Excel Worksheet and the cells within it:

并访问和操作 Excel 工作表及其中的单元格:

Excel::_WorksheetPtr pWksheet = pXL->ActiveSheet;  
Excel::RangePtr pRange = pWksheet->Cells;  
double value = pRange->Item[1][1];  
pRange->Item[1][1] = 5.4321; 

And so on. I have a more in-depth discussion at this following blog posting.

等等。我在以下博客中进行了更深入的讨论。

回答by Bill Forster

A low tech way I have used on a couple of projects is to make a simple script/macro/whatever that runs an external program. Write that external program in C++. Get that external program to read its input from and write its output to a .csv file (simple comma separated value text file). Excel can easily read and write .csv files, so this setup gives you everything you need to craft a viable solution.

我在几个项目中使用的一种低技术方法是制作一个简单的脚本/宏/任何运行外部程序的东西。用 C++ 编写外部程序。获取该外部程序以从中读取其输入并将其输出写入 .csv 文件(简单的逗号分隔值文本文件)。Excel 可以轻松读取和写入 .csv 文件,因此此设置可为您提供制定可行解决方案所需的一切。

回答by Goz

This can all be done via the IDispatch interface. It can get really bloody complicated quickly (Cheers Microsoft) but at least once you've got your head round Excel you'll find integrating with any other MS application easy too :)

这一切都可以通过 IDispatch 接口完成。它很快就会变得非常复杂(干杯微软),但至少一旦你掌握了 Excel,你会发现与任何其他 MS 应用程序集成也很容易:)

Fortunately there is someone over on codeguruwho has made the process nice and easy. Once I'd read through that code I started to get my head round what excel was doing and, furthermore, i found it became REALLY easy to extend it to do other things that I wanted. Just remember that you are sending commands to Excel via the IDispatch interface. This means you need to think about how YOU would do something to figure out how to do it programatically.

幸运的是,有人在codeguru上使这个过程变得简单而轻松。一旦我通读了该代码,我就开始了解 excel 正在做什么,此外,我发现扩展它来做我想做的其他事情变得非常容易。请记住,您是通过 IDispatch 接口向 Excel 发送命令。这意味着您需要考虑您将如何做某事以弄清楚如何以编程方式进行。

Edit: the code guru example is for Excel 2003 but it should be fairly easy to extend it to 2007 :)

编辑:代码大师示例适用于 Excel 2003,但将其扩展到 2007 应该相当容易:)

回答by Bruce Ikin

I have used a 3rd Party component for this in the past: OLE XlsFile from SM Software(not free, but inexpensive). The advantage of this component over the Microsoft COM components is that you can use it to write XLS files even if Excel is not installed.

我过去曾为此使用过第三方组件:来自SM Software 的OLE XlsFile (不免费,但不贵)。该组件相对于 Microsoft COM 组件的优势在于,即使未安装 Excel,您也可以使用它来编写 XLS 文件。

It also allows you to create speadsheets or workbooks with embedded formulas and formatting, something not possible if you use CSV files as an interchange format.

它还允许您使用嵌入的公式和格式创建电子表格或工作簿,如果您使用 CSV 文件作为交换格式,这是不可能的。

回答by Sebastian

If you need the best performance, writing binary Excel files is the way to go and writing them is not as difficult as reading them. The binary file format is relatively well documented by the OpenOffice.org project:

如果您需要最佳性能,那么编写二进制 Excel 文件是一种方法,并且编写它们并不像阅读它们那么困难。OpenOffice.org 项目对二进制文件格式进行了相对完善的记录:

http://sc.openoffice.org/excelfileformat.pdf

http://sc.openoffice.org/excelfileformat.pdf

and Microsoft has also released the documentation:

微软还发布了文档:

http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Excel97-2007BinaryFileFormat(xls)Specification.xps

http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Excel97-2007BinaryFileFormat(xls)Specification.xps

This solution will work best if you have to write many Excel files, mostly with data and little formatting, and if you don't want to open the files at the same time. If you write a single Excel file to open it afterwards, you can probably use the propsed C++ COM Interface as the other posters have explained.

如果您必须编写许多 Excel 文件(主要是数据和很少的格式),并且不想同时打开这些文件,则此解决方案将最有效。如果你写了一个单独的 Excel 文件然后打开它,你可能可以使用推荐的 C++ COM 接口,正如其他海报所解释的那样。

Using the COM interface will necessitate expensive out-of-process calls unless you write an Excel COM Addin. If you write an Addin that imports your data into the current Excel sheet, filling the sheet will still be much slower than dumping a file, but for a single file at a time this can be acceptable depending on your user scenario. If you do decide to use the COM interface, minimize the number of calls to Excel. Use the methods that allow to insert an array of values if they exist, set style properties by row and column is possible and not per cell.

除非您编写 Excel COM Addin,否则使用 COM 接口将需要昂贵的进程外调用。如果您编写一个将数据导入当前 Excel 工作表的插件,填充工作表仍然比转储文件慢得多,但对于一次单个文件,这可以接受,具体取决于您的用户场景。如果您决定使用 COM 接口,请尽量减少对 Excel 的调用次数。使用允许插入值数组(如果存在)的方法,可以按行和列设置样式属性,而不是每个单元格。

回答by Jeff

It has been a very long time but I have used the Jet OLEDB to get at Excel files. You might start searching in that direction.

已经很长时间了,但我已经使用 Jet OLEDB 来获取 Excel 文件。您可能会开始朝那个方向搜索。

回答by Andrew Keith

Start here with the OpenXml Sdk. Download the SDK from here. The SDK uses .NET, so you might need to use C++.NET

OpenXml Sdk 开始。从这里下载 SDK 。SDK 使用 .NET,因此您可能需要使用 C++.NET