How create and excel file from cpp with Win32 or COM

Harshithraj1871 1,681 Reputation points
2024-01-22T06:53:47.7866667+00:00

Hi,

I'm working on the Winui3 desktop app in cpp. I have a table of data and I want to export it to Microsoft Excel format(.xlxs),

How to create a new Excel file and export data to it with Cpp without using 3rd party libs?

Thank You

Microsoft 365 and Office Development Other
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2024-01-22T08:46:50.9433333+00:00

    With C++ CLR integration you can use Microsoft.Office.Interop.Excel Namespace https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel?view=excel-pia


  2. RLWA32 49,536 Reputation points
    2024-01-22T08:49:03.6133333+00:00

    See Microsoft's Open XML SDK for Office


  3. Castorix31 90,521 Reputation points
    2024-01-22T09:38:42.86+00:00

    A way is with Excel Interop.

    Minimal test with Office 2016 in C++/Win32=>

    At beginning :

    #import "C:\Program Files (x86)\Microsoft Office\root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16\mso.dll" rename("RGB", "MSRGB") rename("DocumentProperties", "WordDocumentProperties")  
    #import "C:\Program Files (x86)\Microsoft Office\root\VFS\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB" raw_interfaces_only, rename("Reference", "ignorethis"), rename("VBE", "testVBE")  
    #import "C:\Program Files (x86)\Microsoft Office\root\Office16\Excel.exe" exclude("IFont", "IPicture") rename("RGB", "ignorethis"), rename("DialogBox", "ignorethis"), rename("VBE", "testVBE"), rename("ReplaceText", "EReplaceText"), rename("CopyFile","ECopyFile"), rename("FindText", "EFindText"), rename("NoPrompt", "ENoPrompt")
    

    Test :

    Excel::_ApplicationPtr pExcel;
    HRESULT hr = pExcel.CreateInstance(L"Excel.Application");
    if (SUCCEEDED(hr))
    {
    				// pExcel->PutVisible(0, true);
    
    				Excel::_WorkbookPtr pWorkbook = pExcel->Workbooks->Add(static_cast<long>(Excel::xlWorksheet));
    				Excel::_WorksheetPtr pWorksheet = pExcel->ActiveSheet;						
    				pWorksheet->PutName(L"Sheet Name");
    				Excel::RangePtr pRange = pWorksheet->Cells;
    				pRange->Item[1][1] = L"Test";
    
    				pWorksheet->SaveAs("E:\\Temp\\test.xlsx");
    				pWorkbook->Close();
    				pExcel->Quit();
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.