C++ buider 操作word
在word中表格的一些地方加入标签,请问如果将标签替换成指定内容。请详解,在线等。
bool TForm1::WordReplace(String docText, String newText, TWordApplication *WordApp, TWordDocument *InterWordDoc)
{
bool bResult = false;
try
{
InterWordDoc->Select();
TVariant charCount = WordApp->ActiveDocument->Characters->Count;
InterWordDoc->Range(TVariant(0), charCount);
WordApp->Selection->Find->ClearFormatting();
WordApp->Selection->Find->Replacement->ClearFormatting();
WordApp->Selection->Find->set_Text(TVariant(docText));
WordApp->Selection->Find->Replacement->set_Text(TVariant(newText));
WordApp->Selection->Find->Forward = true; //从开头向后匹配
WordApp->Selection->Find->Wrap = wdFindContinue;
WordApp->Selection->Find->Format = false; //不论格式
WordApp->Selection->Find->MatchCase = false; //不论大小写
WordApp->Selection->Find->MatchWholeWord = false; //不是整词匹配
WordApp->Selection->Find->MatchByte = false;
WordApp->Selection->Find->MatchWildcards = false; //不是通配
WordApp->Selection->Find->MatchSoundsLike = false;
WordApp->Selection->Find->MatchAllWordForms = false;
WordApp->Selection->Find->Execute();
WordApp->Options->ReplaceSelection = true ;
WordApp->Selection->TypeText(TVariant(newText));
WordApp->Selection->Collapse();
bResult = true;
}
catch (Exception &e)
{
}
return bResult;
}
上面这个方法我用了,但是不知道为啥,一些电脑就可以导出报告,而一些电脑就不能导出。系统一样。错误为C000005
[解决办法]
void __fastcall TForm1::Button2Click(TObject *Sender){ Variant MSWord,vSelect ; try { MSWord=Variant::CreateObject("Word.Application"); } catch(...) { MessageBox(0, "启动 Word 出错, 可能是没有安装Word.", "提示", MB_OK | MB_ICONERROR); MSWord = Unassigned; return; } // 隐藏Word界面 MSWord.OlePropertySet("Visible", true); MSWord.OlePropertyGet("Documents").OleProcedure("Open", "C:\\Doc3.doc"); vSelect = MSWord.OlePropertyGet("Selection"); vSelect.OleProcedure("GoTo",-1,0,0,"asd1"); vSelect.OleProcedure("TypeText","123测试"); MSWord.OlePropertyGet("ActiveDocument").OleProcedure("Save"); MSWord.OleFunction("Quit"); MSWord=Unassigned;}//---------------------------------------