DBGrid数据导出到Excel表格

注意:要在头文件中加上 #include <Comobj.hpp>
//DBGrid数据导出到Excel表格
void __stdcall GridToExcel(TDBGrid *DBGridB,AnsiString titleB,AnsiString fileNameB)    
{ //要导出数据的DBGrid/导出到Excel中的标题/保存Excel的路径
  //判断文件是否存在,并决定是否删除
  if (FileExists(fileNameB))
  {
    if (MessageDlg("文件已经存在,是否删除?",
        mtWarning,TMsgDlgButtons()<<mbOK<<mbCancel,0)==mrOk)
    {
      DeleteFile(fileNameB);
    }
    else
    {
      ShowMessage("放弃操作");
      return;
    }
  }
  //导出到Excel开始
  Variant excelApp,workBook,aft,sheetA,range,bef;
  //检查机器是否安装了Office
  try{
    //打开excel应用程序
    excelApp = CreateOleObject("Excel.Application");
  }
  catch(...)
  {
    ShowMessage("运行Excel出错,请检查本机是否安装了Office!");
    return;
  }
  excelApp.OPS("Visible",true); //使应用程序可见
  //建立一个新的excel文件
  workBook = excelApp.OPG("WorkBooks").OFN("Add");
  workBook = excelApp.OPG("ActiveWorkBook");//打开工作簿
  //显示存在的sheet的数目
  int count = workBook.OPG("sheets").OPG("count");
  aft = workBook.OPG("sheets",count);
  //增加一个sheet
  workBook.OPG("sheets").OPR("Add",bef.NoParam(),aft);
  //当前sheet赋值给sheetA
  sheetA = workBook.OPG("ActiveSheet");
  //将sheet改名为表一
  sheetA.OPS("name","表一");
  //设置表一为横向页面打印,横向用"xlLandscape",纵向用"xlPortrait"
  sheetA.OPG("PageSetup").OPS("Orientation",2);
// 在Excel中设置的相应边距值,在BCB中写入时乘以28.5
   sheetA.OPG("PageSetup").OPS("LeftMargin", 1*28.5);    // 左边距1
   sheetA.OPG("PageSetup").OPS("RightMargin", 1 * 28.5);   // 右边距1
   sheetA.OPG("PageSetup").OPS("TopMargin", 2 * 28.5);     // 上边距2
   sheetA.OPG("PageSetup").OPS("BottomMargin", 2 * 28.5);  // 下边距2
   //设置打印时水平居中对齐
   sheetA.OPG("PageSetup").OPS("CenterHorizontally",true);
//表一的标题***************
  //合并单元格A1到M1,并将A1:M1区域赋值给range
  range = sheetA.OPG("Range","A1:M1");
  range.OFN("Merge",false);//合并用false,拆分用true
  //向单元格中填写内容
  sheetA.OPG("Cells",1,1).OPS("Value",titleB.c_str());
  //设置区域字体
  range.OPG("Cells").OPG("Font").OPS("Name","宋体");
  //设置区域字号大小
  range.OPG("Cells").OPG("Font").OPS("Size",18);
  //设置垂直对齐方式-居中
  range.OPG("Cells").OPS("VerticalAlignment",2);
  //设置水平对齐方式-居中
  range.OPG("Cells").OPS("HorizontalAlignment",3);
//表一的标题结束*************
//表一的表头****************
  for(int i=0;i<DBGridB->DataSource->DataSet->Fields->Count;i++)
  {
    String str = DBGridB->DataSource->DataSet->Fields->Fields[i]->DisplayLabel;
    //向单元格填写内容
    sheetA.OPG("Cells",2,i+1).OPS("Value",str.c_str());
    //设置边框
    sheetA.OPG("Cells",2,i+1).OPG("Borders",1).OPS("LineStyle",1);//左边框
    sheetA.OPG("Cells",2,i+1).OPG("Borders",2).OPS("LineStyle",1);//右边框
    sheetA.OPG("Cells",2,i+1).OPG("Borders",3).OPS("LineStyle",1);//上边框
    sheetA.OPG("Cells",2,i+1).OPG("Borders",4).OPS("LineStyle",1);//下边框
    sheetA.OPG("Cells",2,i+1).OPS("WrapText",true);//设置自动换行
    sheetA.OPG("Cells",2,i+1).OPS("HorizontalAlignment",3);//设置水平居中
  }
//表一的表头结束************
//表一的数据开始************
  DBGridB->DataSource->DataSet->First();
  for(int j=1;j<DBGridB->DataSource->DataSet->RecordCount+1;j++)
  {
    for(int i=0;i<DBGridB->DataSource->DataSet->Fields->Count-1;i++)
    {
      String strA = DBGridB->DataSource->DataSet->Fields->Fields[i]->Text;
      sheetA.OPG("Cells",j+4,i+1).OPS("Value",strA.c_str());
      sheetA.OPG("Cells",j+4,i+1).OPG("Borders",1).OPS("LineStyle",1);//左边框
      sheetA.OPG("Cells",j+4,i+1).OPG("Borders",2).OPS("LineStyle",1);//右边框
      sheetA.OPG("Cells",j+4,i+1).OPG("Borders",3).OPS("LineStyle",1);//上边框
      sheetA.OPG("Cells",j+4,i+1).OPG("Borders",4).OPS("LineStyle",1);//下边框
    }
    if (!DBGridB->DataSource->DataSet->Eof)
    {
      DBGridB->DataSource->DataSet->Next();
    }
  }     
//表一的数据结束***********
  //关闭警告提示
  workBook.OPG("Application").OPS("DisplayAlerts",false);
  //另存为
  workBook.OPR("SaveAs",fileNameB.c_str());
  //关闭工作簿
  workBook.OPR("Close");
  //关闭excel程序
  excelApp.OFN("Quit");
  //结束,如果没有如下代码,Excel线程直到应用程序退出才结束
  excelApp=Unassigned;
  workBook=Unassigned;
  aft=Unassigned;
  sheetA = Unassigned;
  range = Unassigned;
  ShowMessage(titleB+"导出成功!");
}
//写的不好,仅供参考
附:我参考的资料
http://www.ccrun.com/Doc/go.asp?id=529
http://www.ccrun.com/Doc/go.asp?id=543
说明:用户可以通过录制宏,查看宏代码,来获取自己所需要的操作
RX Library 2.75 =============== The Set of Native Delphi Components for Borland Delphi versions 1, 2, 3, 4 & 5 and Borland C++ Builder 1, 3 & 4. 100% Source Code. Last revision date Oct 12, 1999. PLEASE FOLLOW THE INSTRUCTIONS PROVIDED IN THE INSTALLATION SECTION! TABLE OF CONTENTS ----------------- Latest Changes Overview History License Agreement Installation Demonstration Programs Source Files Using GIF Images Copyright Notes NEW FOR VERSION 2.75 -------------------- Delphi 5.0 & C++Builder 4.0 Compatibility New components: TRxLoginDialog New properties, events: TFormPlacement.RegistryRoot TFormPlacement.Version TFontComboBox.UseFonts TRxDBGrid.OnTopLeftChanged TRxDBLookupCombo.DisplayValues TStrHolder.Macros, TStrHolder.OnExpandMacros RxSpin.TValueType.vtHex New routines, methods, constants: SaveClipboardToStream, LoadClipboardFromStream (clipmon.pas) AppFileName, AppVerInfo (rxverinf.pas) XorString, XorEncode, XorDecode (strutils.pas) BUG FIXES. Overview -------- RX Library contains a large number of components, objects and routines for Borland Delphi with full source code. This library is compatible with Borland Delphi 1, 2, 3, 4, 5 and Borland C++ Builder 1, 3, 4. This collection includes over 60 native Delphi components. RX Library is a freeware product. Feel free to distribute the library as long as all files are unmodified and kept together. The authors disclaim all warranties as to this software, whether express or implied, including without limitation any implied warranties of merchantability or fitness for a particular purpose. Use under your own responsibility, but comments (even critique) in English (or in Russian) are welcome. 1. Components: TRxDBLookupCombo provides an incremental search through lookup list by directly typing into the combo control while the lookup list is displayed, LookupSource can refer to TTable, TQuery, TRxQuery or TQBEQuery. It even incrementally searches on the query results and much more... TRx
RX Library 2.75 with Delphi 2009 support (by FlexGraphics software) ====================================================================== The Set of Native Delphi Components for Borland Delphi versions 1, 2, 3, 4, 5, 6, 7, 2005, 2006, 2009 and Borland C++ Builder 1, 3, 4, 5, 6, 2006 & 2009. 100% Source Code. Last revision date Oct 12, 1999. PLEASE FOLLOW THE INSTRUCTIONS PROVIDED IN THE INSTALLATION SECTION! TABLE OF CONTENTS ----------------- Latest Changes Overview History License Agreement Installation Demonstration Programs Source Files Using GIF Images Copyright Notes NEW FOR VERSION 2.75 -------------------- Delphi 5.0 & C++Builder 4.0 Compatibility New components: TRxLoginDialog New properties, events: TFormPlacement.RegistryRoot TFormPlacement.Version TFontComboBox.UseFonts TRxDBGrid.OnTopLeftChanged TRxDBLookupCombo.DisplayValues TStrHolder.Macros, TStrHolder.OnExpandMacros RxSpin.TValueType.vtHex New routines, methods, constants: SaveClipboardToStream, LoadClipboardFromStream (clipmon.pas) AppFileName, AppVerInfo (rxverinf.pas) XorString, XorEncode, XorDecode (strutils.pas) BUG FIXES. Overview -------- This version is the result of long unactivity of RX Library authors and some imperfections and bugs of other RX adaptations to Delphi 6. The authors of this version disclaim all warranties as to this software, whether express or implied, including without limitation any implied warranties of merchantability or fitness for a particular purpose. Use under your own responsibility, but comments (even critique) in English (or in Russian) are welcome. RX Library contains a large number of components, objects and routines for Borland Delphi with full source code. This library is compatible with Borland Delphi 1, 2, 3, 4, 5, 6 and Borland C++ Builder 1, 3, 4. This collection includes over 60 native Delphi components. RX Library is a freeware product. Feel free to distribute the library as long as all files are unmodified and kep
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值