用C++创建、打开和打印Word文件

16

我有三个相关的问题。

我想用C++创建一个名字为word的文件。我希望能够向该文件发送打印命令,以便文件被打印而无需用户手动打开文档,并且我希望能够打开该文档。打开文档应该只是打开word,然后打开文件。

6个回答

15

您可以使用Office Automation完成此任务。您可以在http://support.microsoft.com/kb/196776http://support.microsoft.com/kb/238972上找到关于C++中使用Office Automation的常见问题解答。

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

以下是一些用C++执行各种Word任务的示例:

其中大多数示例展示了如何使用MFC进行操作,但是如果您直接使用ATL或COM,使用COM来操纵Word的概念是相同的。


这是对所问问题的一个很好的答案。我想要指出给其他从其他问题链接到这个答案的人们,这不适用于服务器端使用或者当没有用户登录时。虽然在这个问题中并不是这种情况,但是有些链接到这里的其他问题涉及服务器端使用,在那种情况下 Office 自动化就不再适用了。而对于桌面打印,它则非常适用。 - Samuel Neff

4
作为对类似问题的回答,我建议您查看该页面,在那里作者解释了他采用的解决方案来在没有MsWord、自动化或第三方库的情况下在服务器上生成Word文档。请参考类似问题此页面

2
当您已经拥有文件并想要打印它时,请查看 Raymond Chen 博客上的 此条目。您可以使用“print”这个动词来进行打印。
有关详细信息,请参见 shellexecute MSDN 条目

1

0

我没有与 Microsoft Office 集成的经验,但我猜测有一些 API 可供使用。

然而,如果您想要实现一个基本的格式化输出并将其导出到可在 Word 中处理的文件中,您可能需要查看 RTF 格式。该格式非常容易学习,并由 RtfTextBox(或是 RichTextBox?)支持,它也具有一些打印功能。rtf 格式是 Windows Wordpad(write.exe)使用的相同格式。

这还可以避免依赖 MS Office。


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接