vc++ 调用Word 实现转换格式
此前VB做过这程序,只是格式不一样。之前是做Word->Html
现在是Word->Txt 。
不熟悉VC 弄得我比较磨蹭。
HandleWord.h
#pragma once
class HandleWord
{
public:
HandleWord(void);
HandleWord(const char* fileName);
~HandleWord(void);
private:
const char* FileName;
public:
void TransFormToTxt();
};
class HandleWord
{
public:
HandleWord(void);
HandleWord(const char* fileName);
~HandleWord(void);
private:
const char* FileName;
public:
void TransFormToTxt();
};
.cpp
这其中SaveAs的变量与VB较之复杂。其参数COleVariant 也弄晕了我。--->Union类型 可变类型。
#include "stdafx.h"
#include "HandleWord.h"
#include "msword.h"
HandleWord::HandleWord()
{
}
HandleWord::HandleWord(const char* fileName)
{
FileName=fileName;
}
HandleWord::~HandleWord()
{
}
void HandleWord::TransFormToTxt()
{
_Application WordApp;
CoInitialize(NULL);
if(!WordApp.CreateDispatch("Word.Application",NULL))
{
//AfxMessageBox("创建Word服务失败!");
exit(1);
return;
}
WordApp.SetVisible(TRUE);
COleVariant vTrue((short)TRUE),vFalse((short)FALSE),vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
Documents docs=WordApp.GetDocuments();
docs.Open(COleVariant(FileName),
vFalse,vFalse,vFalse,COleVariant(""),COleVariant(""),
vFalse,COleVariant(""),COleVariant(""),
COleVariant((short)0),COleVariant("UTF-8")
,vTrue,vFalse,COleVariant((short)0),vFalse,
COleVariant(""));
_Document active_doc;
active_doc = WordApp.GetActiveDocument();
active_doc.SaveAs(COleVariant("D:\\12.txt"),
COleVariant((short)2),
vFalse, COleVariant(""),vFalse, COleVariant(""),
vFalse,vTrue,vFalse,vFalse,vFalse,COleVariant("936"),//COleVariant(L"UTF-8")
vFalse,vFalse,COleVariant((short)0),vFalse);
WordApp.Quit(vOpt, vOpt, vOpt);
}
#include "HandleWord.h"
#include "msword.h"
HandleWord::HandleWord()
{
}
HandleWord::HandleWord(const char* fileName)
{
FileName=fileName;
}
HandleWord::~HandleWord()
{
}
void HandleWord::TransFormToTxt()
{
_Application WordApp;
CoInitialize(NULL);
if(!WordApp.CreateDispatch("Word.Application",NULL))
{
//AfxMessageBox("创建Word服务失败!");
exit(1);
return;
}
WordApp.SetVisible(TRUE);
COleVariant vTrue((short)TRUE),vFalse((short)FALSE),vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
Documents docs=WordApp.GetDocuments();
docs.Open(COleVariant(FileName),
vFalse,vFalse,vFalse,COleVariant(""),COleVariant(""),
vFalse,COleVariant(""),COleVariant(""),
COleVariant((short)0),COleVariant("UTF-8")
,vTrue,vFalse,COleVariant((short)0),vFalse,
COleVariant(""));
_Document active_doc;
active_doc = WordApp.GetActiveDocument();
active_doc.SaveAs(COleVariant("D:\\12.txt"),
COleVariant((short)2),
vFalse, COleVariant(""),vFalse, COleVariant(""),
vFalse,vTrue,vFalse,vFalse,vFalse,COleVariant("936"),//COleVariant(L"UTF-8")
vFalse,vFalse,COleVariant((short)0),vFalse);
WordApp.Quit(vOpt, vOpt, vOpt);
}
其中的msword.h 与 msword.cpp 根据不同Word版本似乎不同。这个可以下载。
解释下:
active_doc.SaveAs(COleVariant("D:\\12.txt"),
COleVariant((short)2),....
COleVariant((short)2),....
COleVariant((short)2) 是类型,需要自己看msdn ,不过最好还是按照msdn弄个Enum,或者弄个#define txt 2 也好点。
COleVariant("936")是Encoding。(技巧的确如vckbase所言,用宏录制,看其VB代码,再翻译成VC)
其余参数msdn之。