如果您要在應用程序中處理Word文檔,可以參考MSDN. Lori Turner. Automating Microsoft Office 97 and Office 2000,該文內容詳細全面,但是要在C++程序中導出Word文檔,按照文中的方法來處理是很麻煩的,特別是需要填寫的參數太多,所以我們考慮生成正確的VB腳本,然后執行生成Word文檔的操作,這個方法的優點在于:一方面可以少填寫參數;另一方面可以使用在Word中錄制的宏腳本,而只需作少量的修改。我們給出了一些簡單的函數來方便生成Word文檔(主要是簡單的表格)和直接運行內存中的VB腳本,此外,還附帶了一個小小的例子。
//創建Word文檔 std::string create_new(); //保存Word文檔 std::string close_save(const char* filename); //selection 往下移,以繼續生成下一元素 std::string move_down(); //插入分段符 std::string put_Paragraph(); //添加標題 std::string put_title(const char* title, const char* title_type="標題 1", int align=ALIGN_LEFT); //添加“標題1” std::string put_title1(const char* title, int align=ALIGN_CENTER); //添加“標題2” std::string put_title2(const char* title, int align=ALIGN_LEFT); //添加“標題3” std::string put_title3(const char* title, int align=ALIGN_LEFT); //添加紅色警告信息 std::string add_warning_msg(const char* msg="無數據"); //添加表格的一行數據(不用此函數) std::string add_grid_ln(const char* line); //添加表格 std::string put_grid(const char* content);
//運行腳本 extern "C" void RunScript(const char* script_str); 下面是一個小例子,我們期望它在您的計算機上能夠很好的運行,程序將生成一個Word文檔,路徑位于c:\test.doc,計算機上需要安裝Word XP。 int main(int argc, char* argv[]) { ostringstream ostr; ostr<<create_new();
ostr<<put_title1("統計結果"); ostr<<put_title2("統計子項詳細信息");
std::string str_buffer; read_file_as_grid_content("tab.txt", str_buffer);
ostr<<put_Paragraph(); ostr<<put_grid(str_buffer.c_str()); ostr<<close_save("c:\\test.doc");
//輸出到文件看看VB腳本的內容 /* std::ofstream ofile; ofile.open("c:\\temp.vbs"); ofile<<ostr.str().c_str(); ofile.close(); */ //BeginWaitCursor(); RunScript( ostr.str().c_str() );//運行生成的腳本 //EndWaitCursor(); return 0; }
|