https://gist.github.com/meki/7e8b462a8d36919d778f
https://www.c-sharpcorner.com/article/word-automation-using-C-Sharp/
ざっくり言うと上記なのだけれど、C++CLIの場合はコピペでは到底動かない。
Object^ oMissing = ::System::Reflection::Missing::Value;
Object^ oTrue = true; Object^ oFalse = false;
Object^ filename = ::System::IO::Directory::GetCurrentDirectory() + "\\out.docx";
https://gist.github.com/meki/7e8b462a8d36919d778f
ではSaveAs2の引数はファイル名のみだが、C++CLIでは以下のように全て指定する。
Object^ filename = ::System::IO::Directory::GetCurrentDirectory() + "\\out.docx"; document->SaveAs2( filename, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing );
using namespace Microsoft::Office::Interop::Word;
これはやらない方がいい。
Microsoft::Office::Interop::Word::Systemというのがあり、using namespaceをするとそれと衝突してコンパイルが通らなくなる。
#include "pch.h" using namespace System; /// <summary> /// 文書の末尾位置を取得する. /// </summary> /// <returns></returns> int getLastPosition(Microsoft::Office::Interop::Word::Document^ document) { return document->Content->End - 1; } /// <summary> /// 文書の末尾にテキストを追加する. /// </summary> void addTextSample( Microsoft::Office::Interop::Word::Document^ document, Microsoft::Office::Interop::Word::WdColorIndex color, System::String^ text) { Object^ before = getLastPosition(document); Object^ dce = document->Content->End - 1; Microsoft::Office::Interop::Word::Range^ rng = document->Range(dce, dce); rng->Text += text; Object^ after = getLastPosition(document); document->Range(before, after)->Font->ColorIndex = color; } int main(array<::System::String ^> ^args) { Microsoft::Office::Interop::Word::Application^ word = gcnew Microsoft::Office::Interop::Word::Application(); word->Visible = false; Object^ oMissing = ::System::Reflection::Missing::Value; Microsoft::Office::Interop::Word::Document^ document = word->Documents->Add(oMissing, oMissing, oMissing, oMissing); Object^ oTrue = true; Object^ oFalse = false; //////////////////////////////////////// // テキストを追加 addTextSample(document, Microsoft::Office::Interop::Word::WdColorIndex::wdGreen, "Hello, "); addTextSample(document, Microsoft::Office::Interop::Word::WdColorIndex::wdRed, "World"); //////////////////////////////////////// // 名前を付けて保存 Object^ filename = ::System::IO::Directory::GetCurrentDirectory() + "\\out.docx"; document->SaveAs2( filename, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing ); // 文書を閉じる ((Microsoft::Office::Interop::Word::_Document^)(document))->Close(oFalse, oMissing, oMissing); ((Microsoft::Office::Interop::Word::_Application^)word)->Quit(oMissing, oMissing, oMissing); return 0; }