如何使用 C++ 处理 excel 个文件?

how to handle excel files using C++?

我是 C++ 的新手,我想使用 C++ 在 excel 电子表格中输入值,我知道我们可以使用 fstream 处理文件,但如何获取特定的列或行使用此方法。

如果您想操作 .xlsx 文件,

C++ 可能不是最佳选择。您最好使用 Excel 使用 VBA 中的宏,或者您可以使用 VSTO 编写 Excel 插件。如果您真的需要坚持使用 C++,请考虑您是否真的需要本机 Excel 格式。也许 .csv 文件就足够了。

如果您想坚持使用 C++(尽管上面有评论),此示例将让您了解使用 C++ 自动化 Excel 应用程序所需的编码工作(就像您可能在VBA 或 C#) 而不是使用已知文件格式(使用第三方库)操作文件。该示例在后台打开现有工作表,将 Sheet1 上单元格 A1 中的值加 1,然后保存。

对于您的情况,这是否是合适或有效的解决方案将取决于您尝试对文件执行的具体操作。

注意。仅适用于 MS Visual Studio 编译器。

导入库的硬编码路径在您的计算机上可能不同,并且可能取决于您的 Excel 版本。

//Import all the type libraries

#import "C:\Program Files\Microsoft Office\Root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16\MSO.dll" \
    rename("RGB","RGB_mso") rename("DocumentProperties","DocumentProperties_mso") 

using namespace Office;

#import "C:\Program Files\Microsoft Office\root\vfs\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"

using namespace VBIDE;

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

#include <iostream>
using namespace std;

int main()
{
    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  
    Excel::_ApplicationPtr pXL;
    if (FAILED(pXL.CreateInstance("Excel.Application")))
    {
        cout << "Could not create instance of Excel" << endl;
        return 1;
    }

    try
    {
        //Uncomment this to see what is going on during each step
        //pXL->Visible = true;

        Excel::_WorkbookPtr pWb = pXL->Workbooks->Open(L"c:\temp\testbook.xlsx");

        //Gets number from cell A1 in Sheet1 and increments
        Excel::_WorksheetPtr pSheet = pWb->Worksheets->Item[L"Sheet1"];
        Excel::RangePtr pRng = pSheet->Cells;
        _variant_t val = pRng->Item[1][1];
        double dVal{ val };
        pRng->Item[1][1] = ++dVal;

        pWb->Save();
        pWb->Close();
    }    
    catch (_com_error ce) 
    {
        cout << "Something went wrong" << endl;
        _bstr_t bstrDesc = ce.Description();
        if( ! bstrDesc )
        {
            cout << "  Unknown Error" << endl;
        }
        else
        {
            cout << "  Error text: " << bstrDesc << endl;
        }
    }

    pXL->Quit();
}

编辑:为了回答未说出口的问题,为什么它是 Excel::_ApplicationPtr、Excel::_WorkbookPtr 等,但对于一个范围来说它是 Excel::RangePtr(没有 _)?完全不知道。

OpenXLSX is a great library for reading and writing excel sheets using C++. Its API documentation is not in the Github repo. It can be found here。回购协议中的示例非常广泛和详细。构建说明也很简单。

我已经在 Linux 和 Windows 上试过了(使用 MinGW)。它运行良好,并且在两个操作系统上具有相同的行为。