我有三个相关的问题。
我想用C++创建一个名字为word的文件。我希望能够向该文件发送打印命令,以便文件被打印而无需用户手动打开文档,并且我希望能够打开该文档。打开文档应该只是打开word,然后打开文件。
我有三个相关的问题。
我想用C++创建一个名字为word的文件。我希望能够向该文件发送打印命令,以便文件被打印而无需用户手动打开文档,并且我希望能够打开该文档。打开文档应该只是打开word,然后打开文件。
您可以使用Office Automation完成此任务。您可以在http://support.microsoft.com/kb/196776和http://support.microsoft.com/kb/238972上找到关于C++中使用Office Automation的常见问题解答。
请记住,要使用C++进行Office Automation,您需要了解如何使用COM。
以下是一些用C++执行各种Word任务的示例:
其中大多数示例展示了如何使用MFC进行操作,但是如果您直接使用ATL或COM,使用COM来操纵Word的概念是相同的。
您可以使用自动化来打开 MS Word(在后台或前台),然后发送所需的命令。
一个很好的起点是知识库文章使用 Visual C++ 进行 Office 自动化。
一些 C 源代码可在如何使用 Visual C++ 访问 Automation 的 DocumentProperties中找到(标题说是 C++,但实际上是纯 C)。
我没有与 Microsoft Office 集成的经验,但我猜测有一些 API 可供使用。
然而,如果您想要实现一个基本的格式化输出并将其导出到可在 Word 中处理的文件中,您可能需要查看 RTF 格式。该格式非常容易学习,并由 RtfTextBox(或是 RichTextBox?)支持,它也具有一些打印功能。rtf 格式是 Windows Wordpad(write.exe)使用的相同格式。
这还可以避免依赖 MS Office。
我的解决方案是使用以下命令:
start /min winword <filename> /q /n /f /mFilePrint /mFileExit
这允许用户指定打印机、副本数量等。
将<filename>
替换为文件名。如果文件名包含空格,则必须用双引号括起来。(例如:file.rtf
,"A File.docx"
)
它可以放置在系统调用中,如下所示:
system("start /min winword <filename> /q /n /f /mFilePrint /mFileExit");
这里有一个C++头文件,其中包含处理此问题的函数,因此如果您经常使用它,则不必记住所有开关:
/*winword.h
*Includes functions to print Word files more easily
*/
#ifndef WINWORD_H_
#define WINWORD_H_
#include <string.h>
#include <stdlib.h>
//Opens Word minimized, shows the user a dialog box to allow them to
//select the printer, number of copies, etc., and then closes Word
void wordprint(char* filename){
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /min winword \"");
strcat(command, filename);
strcat(command, "\" /q /n /f /mFilePrint /mFileExit");
system(command);
delete command;
}
//Opens the document in Word
void wordopen(char* filename){
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /max winword \"");
strcat(command, filename);
strcat(command, "\" /q /n");
system(command);
delete command;
}
//Opens a copy of the document in Word so the user can save a copy
//without seeing or modifying the original
void wordduplicate(char* filename){
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /max winword \"");
strcat(command, filename);
strcat(command, "\" /q /n /f");
system(command);
delete command;
}
#endif