C++中實現把表的數據導出到EXCEL並打印實例代碼。本站提示廣大學習愛好者:(C++中實現把表的數據導出到EXCEL並打印實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是C++中實現把表的數據導出到EXCEL並打印實例代碼正文
實現把表的數據導出到EXCEL並打印實例代碼
首先加入這兩句:
#include "utilcls.h" #include "comobj.hpp"
下面正式開始:
void __fastcall TMainForm::ToExcel(TADOQuery *TT,AnsiString str)
{//TT為被導出數據的表,str為命令(具體看代碼底部的if語句)
#define PG OlePropertyGet
#define PS OlePropertySet
#define FN OleFunction
#define PR OleProcedure
Variant excel;
try
{
excel=CreateOleObject("Excel.Application"); //啟動Excel
}
catch(...)
{
ShowMessage("無法啟動Excel,請檢查是否已經安裝EXCEL!");
}
excel.PS("Visible", (Variant)true); //使Excel啟動後可見
excel.PG("workbooks").FN("Add", 1); //單工作表
for(int i=0;i<TT->FieldCount;i++) //首先給EXCEL添加表的字段名
{
excel.Exec(PropertyGet("Cells")<<1<<i+1).Exec(PropertySet("Value")<<TT->FieldList->Strings[i]);
}
for(int j=0;j<TT->FieldCount;j++)//按字段排列
{ TT->First();
for(int i=0;i<TT->RecordCount;i++)//按數據順序排雷
{
excel.Exec(PropertyGet("Cells")<<i+2<<j+1).Exec(PropertySet("Value")<<TT->FieldByName(TT->FieldList->Strings[j])->AsString);
TT->Next();
}
}
if(str=="導出"){}//如果是導出,就什麼都不干
if(str=="打印")//如果是打印
excel.OlePropertyGet("ActiveWorkBook").OlePropertyGet("ActiveSheet").OleFunction("PrintOut");
if(str=="打印浏覽")//如果是打印浏覽
excel.OlePropertyGet("ActiveWorkBook").OlePropertyGet("ActiveSheet").OleFunction("PrintPreview");
excel.~Variant();
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!