首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ Builder >

怎么用C++ Builder实现指定WORD文件的修改?

2012-03-30 
如何用C++ Builder实现指定WORD文件的修改?急紧急需要将电脑内大量文件封面修改,目前文件搜索功能已完成,

如何用C++ Builder实现指定WORD文件的修改?急
紧急需要将电脑内大量文件封面修改,目前文件搜索功能已完成,需要实现指定WORD的打开,插入文字,保存,退出等动作,哪位高手帮我。
以下是WORD里的宏,如何在CB中实现。
Documents.Open FileName:="E:\test work\出席回执.doc", ConfirmConversions:=False, ReadOnly:= _
  False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
  "", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
  Format:=wdOpenFormatAuto, XMLTransform:=""
  Selection.TypeParagraph
  Selection.MoveUp Unit:=wdLine, Count:=1
  Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
  Selection.Font.Size = 14
  Selection.Font.Name = "宋体"
  Selection.TypeText Text:="1234"
  Selection.TypeParagraph
  Selection.TypeText Text:="5678"
  ActiveDocument.Save
  ActiveWindow.Close

[解决办法]
在BCB 6 中新建一个Application,切换到界面设计部分,在控件Tabs中打开Office2K,拖一个WordApplication,两个WordDocument到Form上,分别命名为WordApp, DestWordDoc,InterWordDoc。添加一个按钮,一个文本框,名字取缺省值。

在Form1的头文件中添加函数 bool TForm1::WordReplace(String docText, String newText, TWordApplication *WordApp, TWordDocument *InterWordDoc);

在 CPP文件中加入其实现:

view plaincopy to clipboardprint?
//简单处理,直接执行替换操作
/**
* 在 InterWordDoc中,使用 newText 替换原来的 docText
*/
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;
}
//简单处理,直接执行替换操作
/**
* 在 InterWordDoc中,使用 newText 替换原来的 docText
*/
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;


在按钮的点击事件中加入如下代码view plaincopy to clipboardprint?
try{
  
WordApp->Connect();
  
// 得到EXE文件所在的路径 ,例如 c:\MyDir
String PathStr = ExtractFilePath(ParamStr(0));
  
//查看 目标文件夹 c:\MyDir\Document是否存在,若不存在,则创建之
if(!DirectoryExists(PathStr + "Document"))
{
if(!CreateDir(PathStr + "Document"))
throw Exception("不能创建目录:" + PathStr + "Document");
}
  
//模板文件
TVariant TemplateFile = PathStr + "DocTemplates\\encash_week_B001.dot";
if(!FileExists(TemplateFile))
{
throw Exception("模板文件不存在!");
}
  
//目标文件
TVariant DestFile = PathStr + "Document\\encash_week_B001_2004003.doc";
  
WordApp->set_Visible(1);//Word文档的打开、替换 置为 可见,1为short值
  
DestWordDoc->ConnectTo(WordApp->Documents->Add());
InterWordDoc->ConnectTo(WordApp->Documents->Add(&TemplateFile, EmptyParam));
  
WordReplace("#YEAR#", "2009", WordApp, InterWordDoc);
WordReplace("#MONTH#", "11", WordApp, InterWordDoc);
WordReplace("#DAY#", IntToStr(15), WordApp, InterWordDoc);
  
WordReplace("#CURRENTTERMCODE#", "HEB-BD-AG9999", WordApp, InterWordDoc);
  
InterWordDoc->Select();
TVariant charCount = WordApp->ActiveDocument->Characters->Count;
InterWordDoc->Range(TVariant(0), charCount);
WordApp->Selection->Copy();
  
DestWordDoc->Select();
charCount = WordApp->ActiveDocument->Characters->Count;
DestWordDoc->Range(TVariant(0), charCount);
while (1)
{ //被选中的文档 (DestWordDoc)向下移动10屏,若返回值为0屏,则跳出
if (WordApp->Selection->MoveDown(OleVariant(wdScreen), OleVariant(10), EmptyParam) == 0)
break;
}
  
WordApp->Selection->Paste();
  
//设置第一个表格中单元格的内容
DestWordDoc->Tables->Item(1)->Cell(1,2)->Range->set_Text(WideString("张三"));
DestWordDoc->Tables->Item(1)->Cell(2,8)->Range->set_Text(WideString("乐透乐透"));
DestWordDoc->Tables->Item(1)->Cell(3,2)->Range->set_Text(WideString("新的TouZhuH"));
DestWordDoc->Tables->Item(1)->Cell(4,6)->Range->set_Text(WideString("人民币10000万"));
  
//设置第二个表格中单元格的内容
DestWordDoc->Tables->Item(2)->Cell(1,4)->Range->set_Text(WideString("13124198208216543"));
  
// 读取表格中单元格的内容
WideString str = DestWordDoc->Tables->Item(1)->Cell(2,4)->Range->get_Text();


Edit1->Text = str;
  
//保存对文件所作的修改
DestWordDoc->SaveAs(DestFile);
  
WordApp->Quit(OleVariant(wdDoNotSaveChanges));
WordApp->Disconnect();
  
}
catch(...)
{
ShowMessage("您可能没有安装Word!");
WordApp->Disconnect();
}
try{

WordApp->Connect();

// 得到EXE文件所在的路径 ,例如 c:\MyDir
String PathStr = ExtractFilePath(ParamStr(0));

//查看 目标文件夹 c:\MyDir\Document是否存在,若不存在,则创建之
if(!DirectoryExists(PathStr + "Document"))
{
if(!CreateDir(PathStr + "Document"))
throw Exception("不能创建目录:" + PathStr + "Document");
}

//模板文件
TVariant TemplateFile = PathStr + "DocTemplates\\encash_week_B001.dot";
if(!FileExists(TemplateFile))
{
throw Exception("模板文件不存在!");
}

//目标文件
TVariant DestFile = PathStr + "Document\\encash_week_B001_2004003.doc";

WordApp->set_Visible(1);//Word文档的打开、替换 置为 可见,1为short值

DestWordDoc->ConnectTo(WordApp->Documents->Add());
InterWordDoc->ConnectTo(WordApp->Documents->Add(&TemplateFile, EmptyParam));

WordReplace("#YEAR#", "2009", WordApp, InterWordDoc);
WordReplace("#MONTH#", "11", WordApp, InterWordDoc);
WordReplace("#DAY#", IntToStr(15), WordApp, InterWordDoc);

WordReplace("#CURRENTTERMCODE#", "HEB-BD-AG9999", WordApp, InterWordDoc);

InterWordDoc->Select();
TVariant charCount = WordApp->ActiveDocument->Characters->Count;
InterWordDoc->Range(TVariant(0), charCount);
WordApp->Selection->Copy();

DestWordDoc->Select();
charCount = WordApp->ActiveDocument->Characters->Count;
DestWordDoc->Range(TVariant(0), charCount);
while (1)
{ //被选中的文档 (DestWordDoc)向下移动10屏,若返回值为0屏,则跳出
if (WordApp->Selection->MoveDown(OleVariant(wdScreen), OleVariant(10), EmptyParam) == 0)
break;
}

WordApp->Selection->Paste();

//设置第一个表格中单元格的内容
DestWordDoc->Tables->Item(1)->Cell(1,2)->Range->set_Text(WideString("张三"));
DestWordDoc->Tables->Item(1)->Cell(2,8)->Range->set_Text(WideString("乐透乐透"));
DestWordDoc->Tables->Item(1)->Cell(3,2)->Range->set_Text(WideString("新的TouZhuH"));
DestWordDoc->Tables->Item(1)->Cell(4,6)->Range->set_Text(WideString("人民币10000万"));

//设置第二个表格中单元格的内容
DestWordDoc->Tables->Item(2)->Cell(1,4)->Range->set_Text(WideString("13124198208216543"));

// 读取表格中单元格的内容
WideString str = DestWordDoc->Tables->Item(1)->Cell(2,4)->Range->get_Text();
Edit1->Text = str;

//保存对文件所作的修改
DestWordDoc->SaveAs(DestFile);

WordApp->Quit(OleVariant(wdDoNotSaveChanges));
WordApp->Disconnect();

}
catch(...)
{
ShowMessage("您可能没有安装Word!");
WordApp->Disconnect();


程序就这些。


[解决办法]
一段源代码。有用的话自己看看。

void __fastcall TFormPrintNBD::BtnPrintClick(TObject *Sender)
{
 AnsiString FileName = "Lch\\Mydot1.dot";
 //测试文件是否存在
 if(!FileExists(FileName))
 {
MessageDlg("很包歉,本系统一些重要文件丢失,程序将自动关闭!",mtError,TMsgDlgButtons()<<mbYes, 0 );
Application->Terminate();
 }
try
 {
//文件路径
AnsiString TemplateName = ExtractFilePath(ParamStr(0));;
TVariant PathFileName = TemplateName + FileName;



OleVariant ItemIndex=1;
WordApplication1->Visible=true;
WordApplication1->Connect();//连接Word应用程序

// OleVariant Template=TemplateName;
OleVariant NewTemplate=False;
OleVariant DocumentType;
OleVariant Visible;

WordApplication1->Documents->Add(PathFileName,NewTemplate,DocumentType,Visible);//添加文档
WordDocument1->ConnectTo(WordApplication1->Documents->Item(ItemIndex));

TDateTime curDate=Date(); //取得当前时间
AnsiString DateStr;
DateStr=curDate.FormatString("yyyy")+"年"+curDate.FormatString("mm")+"月"+curDate.FormatString("dd")+"日";


FindAndReplaceField("<1>",DBEditJG->Text);
FindAndReplaceField("<2>",DateStr);

FindAndReplaceField("<3>",DBEditXFFS->Text);
FindAndReplaceField("<4>",DBEditLY->Text);
FindAndReplaceField("<5>",DBEditHH->Text);

FindAndReplaceField("<6>",DBEditBFYName->Text);
 // FindAndReplaceField("<6>", DataModule2->ADOQuery1->FieldValues["BFYName"]);
FindAndReplaceField("<7>",DBEditBFYDW->Text);

FindAndReplaceField("<8>",DBCbBoxBFYZW->Text);
FindAndReplaceField("<9>",DBCbBoxBFYJB->Text);
FindAndReplaceField("<10>",DBEditFYName->Text);
FindAndReplaceField("<11>",DBEditFYDW->Text);
FindAndReplaceField("<12>",DBCbBoxFYZW->Text);

FindAndReplaceField("<13>",DBEditDH->Text);
FindAndReplaceField("<14>",DBMemoWTZY->Text);
FindAndReplaceField("<15>",DBMemoNBYJ->Text);
FindAndReplaceField("<16>",DBEditCBRName->Text);
FindAndReplaceField("<17>",DBMemoBMYJ->Text);

FindAndReplaceField("<18>",DateStr);

//打印本件所有领导批示
AnsiString PSYJ="";
DataModule2->ADOQuery2->First();
for(int i=0;i<DataModule2->ADOQuery2->RecordCount;i++)
{
PSYJ = PSYJ + "("+IntToStr(i+1)+")"+DataModule2->ADOQuery2->FieldByName("批示日期")->AsString + " " + DataModule2->ADOQuery2->FieldByName("领导姓名")->AsString + "批示:" + DataModule2->ADOQuery2->FieldByName("领导附加批示")->AsString + " ";
DataModule2->ADOQuery2->Next();
}

FindAndReplaceField("<19>",PSYJ);
FindAndReplaceField("<20>",DBEditXFGJ->Text+DBEditXFNo->Text);


 }
 catch(...)
 {
MessageDlg("您可能没有安装Word!",mtError,TMsgDlgButtons()<<mbYes, 0 );
WordApplication1->Disconnect();
 }
}

//--------------------------
void __fastcall TFormPrintNBD::FindAndReplaceField(AnsiString OldWord,AnsiString NewWord)
{
TVariant RepPara=wdReplaceAll;
TVariant EmptyPara=TNoParam();

WordApplication1->Selection->Find->Text=WideString(OldWord).c_bstr();
WordApplication1->Selection->Find->Replacement->Text=WideString(NewWord).c_bstr();
WordApplication1->Selection->Find->Execute(&EmptyPara,&EmptyPara,&EmptyPara,&EmptyPara,
&EmptyPara,&EmptyPara,&EmptyPara,&EmptyPara,
&EmptyPara,&EmptyPara,&RepPara,&EmptyPara,
&EmptyPara,&EmptyPara,&EmptyPara);


}



[解决办法]

C/C++ code
try 
{
CoInitialize(NULL);
WordApp=CreateOleObject("Word.Application");


}
catch(...)
{
MessageBox(Form1->Handle,"创建word接口错误,确定是否真确安装word!"
,"错误",MB_ICONSTOP);
return;
}
//---------------------------
Form1->Button5->Enabled=false;
Form1->Button6->Enabled=true;
//---------------------------
int count=Form1->ListView1->Items->Count;
for(int i=0;i <count;i++)
{
InFile=Form1->ListView1->Items->Item[i]->SubItems->Strings[0];
OutFile=Form1->Edit1->Text+"\\";
OutFile+=ExtractFileName(InFile);
Form1->Label3->Caption="正在处理"+InFile;
AnsiString TmpFile=ExtractFilePath(GetModuleName(unsigned(HInstance)))
+"\\templet.doc";
//---------------------
if(Form1->stop==true)
break;
/////////////////////////////////////////////////////////
//添加页眉水印
    WordDocPtr=WordApp.OlePropertyGet("Documents");
WordDoc=WordDocPtr.OleFunction("Open",TmpFile.c_str());
WordApp.OlePropertySet("Visible",false);
//Selection接口
WordSel=WordApp.OlePropertyGet("Selection");
//切换到页眉 全选 复制
View=WordApp.OlePropertyGet("ActiveWindow")
.OlePropertyGet("ActivePane").OlePropertyGet("View");
View.OlePropertySet("SeekView",9);
WordSel.OleFunction("WholeStory");
WordSel.OleFunction("Copy");
WordDoc.OleFunction("Close");
//打开Word文档
WordDocPtr=WordApp.OlePropertyGet("Documents");
WordApp.OlePropertySet("Visible",false);
WordDoc=WordDocPtr.OleFunction("Open",InFile.c_str());
//Selection接口
WordSel=WordApp.OlePropertyGet("Selection");
ActiveDocument=WordApp.OlePropertyGet("ActiveWindow");
View=ActiveDocument.OlePropertyGet("ActivePane")
.OlePropertyGet("View");
View.OlePropertySet("SeekView",9);
WordSel.OleFunction("WholeStory");
WordSel.OleFunction("PasteAndFormat",0);
WordSel.OleFunction("TypeBackspace");
//另存为
WordDoc.OleFunction("SaveAs",OutFile.c_str());
WordDoc.OleFunction("Close");
MessageBox(NULL,"页眉水印添加成功,\n下一步添加页脚。","",MB_OK);
//-------------------------
//添加页脚
WordDocPtr=WordApp.OlePropertyGet("Documents");
WordDoc=WordDocPtr.OleFunction("Open",TmpFile.c_str());
//---------------------------
//获取模板信息
//页眉设置定义至
Variant PaperSize;
Variant TopMargin;
Variant BottomMargin;
Variant LeftMargin;
Variant RightMargin;
Variant Gutter;
Variant PageWidth;
Variant PageHeight;
Variant Orientation;
Variant HeaderDistance;
Variant FooterDistance;
Variant SectionStart;
Variant LayoutMode;
Variant CharsLine;
Variant LinesPage;

WordPage=WordDoc.OlePropertyGet("PageSetup");
//获取设置信息
PaperSize=WordPage.OlePropertyGet("PaperSize");
TopMargin=WordPage.OlePropertyGet("TopMargin");
BottomMargin=WordPage.OlePropertyGet("BottomMargin");
LeftMargin=WordPage.OlePropertyGet("LeftMargin");
RightMargin=WordPage.OlePropertyGet("RightMargin");
Gutter=WordPage.OlePropertyGet("Gutter");
PageWidth=WordPage.OlePropertyGet("PageWidth");
PageHeight=WordPage.OlePropertyGet("PageHeight");
Orientation=WordPage.OlePropertyGet("Orientation");


HeaderDistance=WordPage.OlePropertyGet("HeaderDistance");
FooterDistance=WordPage.OlePropertyGet("FooterDistance");
SectionStart=WordPage.OlePropertyGet("SectionStart");
LayoutMode=WordPage.OlePropertyGet("LayoutMode");
CharsLine=WordPage.OlePropertyGet("CharsLine");
LinesPage=WordPage.OlePropertyGet("LinesPage");
//-------------------------
//Selection接口
WordSel=WordApp.OlePropertyGet("Selection");
//切换到页脚
View=WordApp.OlePropertyGet("ActiveWindow")
.OlePropertyGet("ActivePane").OlePropertyGet("View");
View.OlePropertySet("SeekView",10);
WordSel.OleFunction("WholeStory");
WordSel.OleFunction("Copy");
//WordDoc.OleFunction("Save");
WordDoc.OleFunction("Close");
//打开Word文档
WordDocPtr=WordApp.OlePropertyGet("Documents");
WordDoc=WordDocPtr.OleFunction("Open",OutFile.c_str());
ActiveDocument=WordApp.OlePropertyGet("ActiveWindow");
WordSel=WordApp.OlePropertyGet("Selection");
View=ActiveDocument.OlePropertyGet("ActivePane")
.OlePropertyGet("View");
View.OlePropertySet("SeekView",10);
WordSel.OleFunction("WholeStory");
WordSel.OleFunction("PasteAndFormat",0);
WordSel.OleFunction("TypeBackspace");
View.OlePropertySet("SeekView",0);
MessageBox(NULL,"页脚添加成功,\n下一步添加字符。","",MB_OK);
//Selection接口
WordSel=WordApp.OlePropertyGet("Selection");
WordFind=WordSel.OlePropertyGet("Find");
//------------------------------
//查找替换 添加固定字符
Variant vValue=false;
Variant Font;
Variant Replacement;
Variant Size;

WordFind=WordSel.OlePropertyGet("Find");
WordFind.OleFunction("ClearFormatting");
WordFind.OlePropertySet("MatchCase",false);
WordFind.OlePropertySet("MatchWholeWord",true);
WordFind.OlePropertySet("Text","  ");
WordFind.OlePropertySet("Wrap",1);
WordFind.OlePropertySet("Forward",true);
WordFind.OlePropertySet("Format",false);
WordFind.OlePropertySet("MatchByte",true);
WordFind.OlePropertySet("MatchWildcards",false);
WordFind.OlePropertySet("MatchSoundsLike",false);
WordFind.OlePropertySet("MatchAllWordForms",false);
WordFind.OlePropertySet("MatchWildcards",false);
WordFind.OlePropertySet("MatchAllWordForms",false);
Replacement=WordFind.OlePropertyGet("Replacement");
Replacement.OlePropertySet("Text","");

vValue=WordFind.OleFunction("Execute");
while(vValue==Variant(true))
{
Font=WordSel.OlePropertyGet("Font");
Size=Font.OlePropertyGet("Size");
  Font.OlePropertySet("Size",(int)Size/2);
Font.OlePropertySet("Color",Variant(-603914241));
WordSel.OleFunction("TypeText","恒谦教育网");
vValue=WordFind.OleFunction("Execute");
}
MessageBox(NULL,"字符添加成功,\n下一步添加超链接。","",MB_OK);
//----------------------
//图片添加固定链接  http://www.hengqian.com
Variant WordItem;
int LCount;
WordRanges=WordDoc.OlePropertyGet("InlineShapes");
HLinks=WordDoc.OlePropertyGet("Hyperlinks");
LCount=WordRanges.OlePropertyGet("Count");


for(int j=0;j <LCount;j++)
{
WordItem=WordRanges.OleFunction("Item",Variant(j+1));
HLinks.OleFunction("Add",WordItem,"http://www.hengqian.com");
}
MessageBox(NULL,"超链接添加成功,\n下一步修改版式。","",MB_OK);
//---------------------------
//修改版式
WordPage=WordDoc.OlePropertyGet("PageSetup");
WordPage.OlePropertySet("PaperSize",PaperSize);
WordPage.OlePropertySet("TopMargin",TopMargin);
WordPage.OlePropertySet("BottomMargin",BottomMargin);
WordPage.OlePropertySet("LeftMargin",LeftMargin);
WordPage.OlePropertySet("RightMargin",RightMargin);
WordPage.OlePropertySet("Gutter",Gutter);
WordPage.OlePropertySet("PageWidth",PageWidth);
WordPage.OlePropertySet("PageHeight",PageHeight);
WordPage.OlePropertySet("Orientation",Orientation);
WordPage.OlePropertySet("HeaderDistance",HeaderDistance);
WordPage.OlePropertySet("FooterDistance",FooterDistance);
WordPage.OlePropertySet("SectionStart",SectionStart);
WordPage.OlePropertySet("LayoutMode",LayoutMode);
WordPage.OlePropertySet("CharsLine",CharsLine);
WordPage.OlePropertySet("LinesPage",LinesPage);
MessageBox(NULL,"修改版式成功,\n下一步关闭文档。","",MB_OK);
//-------------------------
//处理完毕关闭文档
WordDoc.OleFunction("Save");
WordDoc.OleFunction("Close");
Form1->ListView1->Items->Item[i]->SubItems->Strings[1]="完成";
Form1->ProgressBar1->StepIt();
}
Form1->Label3->Caption="处理完成,正在退出Word...";
WordApp.OleFunction("Quit");
CoUninitialize();
Form1->Label3->Caption="任务完成";
MessageBox(Form1->Handle,"任务处理完成","提醒",MB_ICONINFORMATION);

热点排行