从C ++创build,打开和打印一个word文件

我有三个相关的问题。

我想用C ++的名字创build一个word文件。 我希望能够将打印命令发送到此文件,以便打印文件而无需用户打开文档并手动执行,我希望能够打开文档。 打开文档应该打开单词,然后打开文件。

您可以使用Office自动化执行此任务。 您可以在http://support.microsoft.com/kb/196776和http://support.microsoft.com/kb/238972找到有关使用C ++进行Office自动化的常见问题解答。

请记住,要使用C ++进行Office自动化,您需要了解如何使用COM。

以下是一些如何在单词usign C ++中执行各种任务的例子:

大多数这些示例显示如何使用MFC,但使用COM操纵Word的概念是相同的,即使您直接使用ATL或COM。

作为类似问题的答案,我建议你看看这个页面 ,作者解释了他在服务器上生成Word文档的方法,没有MsWord,没有自动化或者第三方库。

当你有这个文件,只是想打印出来,然后在Raymond Chen的博客上看看这个条目 。 您可以使用动词“打印”进行打印。

有关详细信息,请参阅shellexecute msdn条目 。

您可以使用自动化来打开MS Word(在后台或前台),然后发送所需的命令。

使用Visual C ++的知识库文章Office Automation是一个很好的起点

一些C源代码可以在如何使用Visual C ++访问DocumentProperties与自动化 (标题说C ++,但它是纯C)

我没有与Microsoft Office集成的经验,但是我想这里面有一些API可以使用。

但是,如果要完成的是打印格式化输出并将其导出到可以在Word中处理的文件的基本方法,则可能需要查看RTF格式。 这个格式非常简单,并且由RtfTextBox(或者它是RichTextBox?)支持,它也具有一些打印功能。 rtf格式与Windows写字板(write.exe)使用的格式相同。

这也有利于不依赖MS Office来工作。

我的解决方案是使用以下命令:

start /min winword <filename> /q /n /f /mFilePrint /mFileExit 

这允许用户指定打印机,不。 复印件等

<filename>替换<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