Question

I am trying to use the OpenXML SDK 2.5 via C++/CLI. Using the example code at the bottom of this MSDN page (http://msdn.microsoft.com/en-us/library/office/ff478153.aspx) works correctly when compiled with C# - I can open the created file successfully in Excel 2007.

The MSDN example code I translated to C++/CLI as follows:

void CreateSpreadsheetWorkbook(String^ filepath)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    SpreadsheetDocument^ spreadsheetDocument = SpreadsheetDocument::Create(filepath, SpreadsheetDocumentType::Workbook);

    // Add a WorkbookPart to the document.
    WorkbookPart^ workbookpart = spreadsheetDocument->AddWorkbookPart();
    workbookpart->Workbook = gcnew Workbook();

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart^ worksheetPart = workbookpart->AddNewPart<WorksheetPart^>();
    worksheetPart->Worksheet = gcnew Worksheet(gcnew SheetData());

    // Add Sheets to the Workbook.
    Sheets^ sheets = spreadsheetDocument->WorkbookPart->Workbook->AppendChild<Sheets^>(gcnew Sheets());

    // Append a new worksheet and associate it with the workbook.
    Sheet^ sheet = gcnew Sheet();
    sheet->Id = spreadsheetDocument->WorkbookPart->GetIdOfPart(worksheetPart);
    sheet->SheetId = 1;
    sheet->Name = L"mySheet";
    sheets->Append(sheet);

    workbookpart->Workbook->Save();

    // Close the document.
    spreadsheetDocument->Close();
}

The code compiles, but the file created is not complete. Excel 2007 complains about a corrupt file. Upon examining the contents of the xlsx file it looks like the details of the "mySheet"-sheet class does not get written to disk. What am I missing in the C++/CLI code that this is not working correctly?

I am using Visual Studio 2013 targeting .Net Framework 4.0.

Était-ce utile?

La solution

C++/CLI can not instantiate classes like you can do it in C#, multiple in one time. And sometimes you must use AppendChild and not just Append method but I don't know why

   // *** same code like you

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart^ worksheetPart = workbookpart->AddNewPart<WorksheetPart^>();
    SheetData^ sheetData = gcnew SheetData();
    worksheetPart->Worksheet = gcnew Worksheet();
    worksheetPart->Worksheet->AppendChild(sheetData);

    // same code like you 

    sheets->AppendChild(sheet);  // *->AppendChild not just *->Append

    workbookpart->Workbook->Save();

    // Close the document.
    spreadsheetDocument->Close();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top