2011-05-05 51 views
1

我正尝试在C++/CLI中编写一个简单的Hello World应用程序来创建一个我已经发布的Word文档OpenXML SDK - 将C#转换为C++/CLI - 创建的文件已损坏,无法打开

int main(array<String^>^ args) 
{ 
    String^ documentFileName=L"Hello4.docx"; 
    WordprocessingDocument ^myDoc = WordprocessingDocument::Create(documentFileName, WordprocessingDocumentType::MacroEnabledDocument); 
    MainDocumentPart^ mainPart = myDoc->AddMainDocumentPart(); 
    mainPart->Document = gcnew Document(); 
    Body^ body = gcnew Body(); 
    Paragraph^ paragraph = gcnew Paragraph(); 
    Run^ run_paragraph = gcnew Run(); 
    DocumentFormat::OpenXml::Wordprocessing::Text^ text_paragraph = gcnew DocumentFormat::OpenXml::Wordprocessing::Text(L"Hello ..asdks"); 
    run_paragraph->Append(text_paragraph); 
    paragraph->Append(run_paragraph); 
    body->Append(paragraph); 
    mainPart->Document->Append(body); 
    mainPart->Document->Save(); 

    return 0; 
} 

上述程序创建hello.docx文件,但我无法打开所创建的文件,因为它是corrupt.Can请你帮我这个

在此先感谢

+0

您收到的确切错误是什么?或者没有错误,但是'mainPart-> Document-> Save();'什么都不会产生? – 2011-05-06 06:46:04

+0

@Otaku-我没有收到任何错误,但如果我运行上述代码的Hello.docx文件正在创建,但即时通讯无法打开file.it说:“该文件已损坏,它不能打开“ – Greenhorn 2011-05-06 06:54:28

+1

这是连接到文件的'WordprocessingDocument'对象,而不是'Document'子对象。根据[文档](http://msdn.microsoft.com/en-us/library/documentformat.openxml.packaging.openxmlpackage.close.aspx),您应该调用'myDoc-> Close();' – 2011-05-06 13:33:20

回答

0

尝试使用一个局部变量,而不是从属性读回。例如

doc = gcnew Document(); 
mainPart->Document = doc; 

//... 

doc->Append(body); 
doc->Save(); 
+0

我试过上面的答案它不工作。你能建议任何其他解决方案吗? – Greenhorn 2011-05-06 05:25:36