BCB xe7 stringgrid 导入导出excel

时间:2021-10-18 00:53:13
           如题,要实现一个stringgrid的导入导出功能,我知道有很多人会回复我说之前有好多资料了。but由于用的是xe7,好多资料的程序运行都有错,而且很多只是贴了一部分,上个月才开始接触,求指导求稍微完整一点的代码,因为急用只好厚着脸皮来求教了, BCB xe7 stringgrid 导入导出excel小女子在这里谢过各位了

9 个解决方案

#1


BCB xe7 stringgrid 导入导出excelxe7还没用 ,,纠结 关注下 。。。。。

#2



function ExportStrGridToExcel(Args: array of const): Boolean;
var
  iCount, jCount: Integer;
  XLApp: Variant;
  Sheet: Variant;
  I: Integer;
begin
  Result := False;
  if not VarIsEmpty(XLApp) then
  begin
    XLApp.DisplayAlerts := False;
    XLApp.Quit;
    VarClear(XLApp);
  end;

  try
    XLApp := CreateOleObject('Excel.Application');
  except
    Exit;
  end;

  XLApp.WorkBooks.Add;
  XLApp.SheetsInNewWorkbook := High(Args) + 1;

  for I := Low(Args) to High(Args) do
  begin
    with TStringGrid(Args[I].VObject) do
    begin 
      XLApp.WorkBooks[1].WorkSheets[I+1].Name := Name;
      Sheet := XLApp.Workbooks[1].WorkSheets[Name];

      for jCount := 0 to RowCount - 1 do
      begin
        for iCount := 0 to ColCount - 1 do
        begin
          Sheet.Cells[jCount + 1, iCount + 1] := Cells[iCount, jCount];
        end;
      end;
    end;
  end;
  XlApp.Visible := True;  
end;




#3


ccrun的代码,供你参考
读取excel

void __fastcall TForm1::Button4Click(TObject *Sender)
{
StringGrid1->Cells[0][0]="序号";
StringGrid1->Cells[1][0]="交易码";
StringGrid1->Cells[2][0]="开始时间";
StringGrid1->Cells[3][0]="内容";
StringGrid1->Cells[4][0]="金 额";
StringGrid1->Cells[5][0]="号码";
int i=0;
StringGrid1->RowCount=2;
ADOQuery1->Open();
while(!ADOQuery1->Eof)
    {
        i++;
        StringGrid1->Cells[0][i]=ADOQuery1->FieldByName("序号")->AsInteger;
        StringGrid1->Cells[1][i]=ADOQuery1->FieldByName("交易码")->AsString;
        StringGrid1->Cells[2][i]=ADOQuery1->FieldByName("开始时间")->AsString;
        StringGrid1->Cells[3][i]=ADOQuery1->FieldByName("内容")->AsString;
        StringGrid1->Cells[4][i]=ADOQuery1->FieldByName("金 额")->AsInteger;
        StringGrid1->Cells[5][i]=ADOQuery1->FieldByName("号码")->AsString;
        ADOQuery1->Next();
        StringGrid1->RowCount++;
    }
ADOQuery1->Close();        
}
//---------------------------------------------------------------------------


导出excel

//---------------------------------------------------------------------------
#include<Comobj.hpp>
#include<Utilcls.h>

//---------------------------------------------------------------------------
void __fastcall  TForm1::SaveToExcel(char * FileName)
{
Variant ex,wk,sht,Range; //ole万能变量,定义excel对象使用
int FieldType[10]={0,0,0,0,2,0,0,0};
try{
 ex=CreateOleObject("Excel.Application"); //启动Excel
 wk=ex.OlePropertyGet("ActiveWorkBook");//创建工作簿对象
 ex.OlePropertyGet("WorkBooks").OleFunction("Add");//添加一个工作薄
 sht=ex.OlePropertyGet("ActiveSheet");//创建工作区
 }
 catch(...)
 {
  MessageDlg("无法启动Excel,可能尚未安装或文件已经损坏!",mtError,TMsgDlgButtons()<<mbYes,0);
  return;
 }


 int iSRow=0;
 int iSCol=0;

 char *cRange;
 cRange=CountCol("A1:", StringGrid1->ColCount - iSCol, 1);

 Range = sht.OlePropertyGet("Range",cRange);
 Range.OleFunction("Merge", false);
 //Range.OlePropertySet("VerticalAlignment", Edit1->Text.ToInt());//居中
 Range.OlePropertySet("HorizontalAlignment",3);//居中
 Range.OlePropertyGet("Interior").OlePropertySet("ColorIndex",24);
 Range .OlePropertyGet("Borders",1).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",2).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",3).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",4).OlePropertySet("LineStyle",1);

 ex.OlePropertySet("Caption","查询结果转入EXCEL:");
 ex.OlePropertySet("StatusBar","       【SQL TOOLS】 WGHSoft.ICBC   Tel:0571-87924880  Email: wghsoft@126.com");
 sht.OlePropertySet("Name", "核对单");
 sht.OlePropertyGet("Cells",1,1).OlePropertySet("Value","测 试 EXCEL");
 sht.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Name","华文中宋");
 sht.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Size",28);

 int i=2;

 for(int row=iSRow;row<StringGrid1->RowCount;row++,i++)
        for(int j=1, col=iSCol;col<StringGrid1->ColCount;col++,j++){
                if(i==2) ex.OlePropertyGet("Cells",j).OlePropertySet("ColumnWidth", StringGrid1->ColWidths[j-1]/7); //宽
                if(i%2==0)
                        sht.OlePropertyGet("Cells",i,j).OlePropertyGet("Interior").OlePropertySet("Color",RGB(213,251,206));
                        else
                        sht.OlePropertyGet("Cells",i,j).OlePropertyGet("Interior").OlePropertySet("Color",RGB(188,244,254));

                        switch(FieldType[col-1]){
                                case 2:
                                        if(BigData(StringGrid1->Cells[col][row].c_str()))
                                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("NumberFormatLocal","@");
                                        break;
                                default:
                                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("NumberFormatLocal","@");
                                        break;
                                }
                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("Value", Trim(StringGrid1->Cells[col][row]).c_str());
                      }

 cRange=CountCol("A2:", StringGrid1->ColCount - iSCol, i-1);

 Range = sht.OlePropertyGet("Range", cRange);
 Range .OleProcedure("Select");
 Range .OlePropertyGet("Borders",1).OlePropertySet("LineStyle",1);//边框
 Range .OlePropertyGet("Borders",2).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",3).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",4).OlePropertySet("LineStyle",1);

 Range .OlePropertySet("RowHeight", 20); //行高

 sht.OleFunction("SaveAs",FileName);  //表格保存

 ex.OlePropertySet("Visible",(Variant)true); //使Excel可见

}

//----------------------------------------------

快速导出excel

String RemoveExtendName(String sFileName)//去除后缀
{
String dFileName;

if(sFileName.Pos("."))
        dFileName=sFileName.SubString(1,sFileName.Pos(".")-1);
                else dFileName=sFileName;
return  dFileName;
}

//----------------------------------------------------------
void __fastcall TForm1::Button5Click(TObject *Sender)
{
String FileName=RemoveExtendName("c:/wsj.htm");
ToHtml(StringGrid1, FileName.c_str(),"测试 StringGrid to Excel");
}


//---------------------------------------------------------------------------

#4


我以前写过的OLE相关代码,有一些瑕疵的。目前在我自己用的库中,支持从ListView/StringGrid/DBGrid等控件中导入/导出到Excel/Csv/Word等格式,已经修正很多问题。

#5


引用 4 楼 ccrun 的回复:
我以前写过的OLE相关代码,有一些瑕疵的。目前在我自己用的库中,支持从ListView/StringGrid/DBGrid等控件中导入/导出到Excel/Csv/Word等格式,已经修正很多问题。

BCB xe7 stringgrid 导入导出excel
能分享一下吗?

#6


我在05年时写过一个将StringGrid、TreeView或DBGrid控件中的数据导出到Excel或WPS表格的函数集,2011年01月完善到XE,目前完美支持XE全系列

iExcelToolsW.cpp



  #include "iExcelToolsW.h" // 一组数据导出到Excel的工具集

//  #include "iExcelToolsW.cpp" // 一组数据导出到Excel的工具集

#ifndef _iExcelToolsW_cpp_
#define _iExcelToolsW_cpp_

/*
  一个将StringGrid、TreeView或DBGrid控件中的数据导出到Excel或WPS表格的函数集
  www.plm.hk 编写于2005年09月,最后修改于2011年01月
*/

  WideString ExcelRangeW[256]=
  {
    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
    "AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ",
    "BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ",
    "CA","CB","CC","CD","CE","CF","CG","CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ",
    "DA","DB","DC","DD","DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ",
    "EA","EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ",
    "FA","FB","FC","FD","FE","FF","FG","FH","FI","FJ","FK","FL","FM","FN","FO","FP","FQ","FR","FS","FT","FU","FV","FW","FX","FY","FZ",
    "GA","GB","GC","GD","GE","GF","GG","GH","GI","GJ","GK","GL","GM","GN","GO","GP","GQ","GR","GS","GT","GU","GV","GW","GX","GY","GZ",
    "HA","HB","HC","HD","HE","HF","HG","HH","HI","HJ","HK","HL","HM","HN","HO","HP","HQ","HR","HS","HT","HU","HV","HW","HX","HY","HZ",
    "IA","IB","IC","ID","IE","IF","IG","IH","II","IJ","IK","IL","IM","IN","IO","IP","IQ","IR","IS","IT","IU","IV"
  };
  Variant ex,newxls,sh;
  int tExcelSumRow=0; // 取得Excel文件可以使用的总行数,固定为65536
  int tExcelSumCol=0; // 取得Excel文件可以使用的总列数,固定为256
//---------------------------------------------------------------------------
  int iStartupExcel( // 启动Excel
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      try
      {
        ex=Variant::CreateObject((WideString)L"Excel.Application"); // 启动Excel
        //ex=Variant::CreateObject((WideString)L"et.Application"); // 如果没有安装Excel就使用WPS表格
      }
      //catch(...)
      //catch(Exception &e)
      catch(Sysutils::Exception &T_MFWV)
      {
          try
          {
            //ex=Variant::CreateObject((WideString)L"Excel.Application"); // 启动Excel
            ex=Variant::CreateObject((WideString)L"et.Application"); // 如果没有安装Excel就使用WPS表格
          }
          //catch(...)
          //catch(Exception &e)
          catch(Sysutils::Exception &T_VWLK)
          {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  (
                    T_MFWV.Message+"\r\n"+T_VWLK.Message+L"\r\n发生意外!"
                  ).w_str()
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
          }
      }
    ex.OlePropertySet((WideString)L"Visible",(Variant)true); // 使Excel启动后可见
    //ex.OlePropertySet("Visible",(Variant)false); // 使Excel启动后不可见
    newxls=(ex.OlePropertyGet((WideString)L"Workbooks")).OleFunction((WideString)L"Add"); // 使用ExcelApp的Exec方法新建一新工作薄
    sh=newxls.OlePropertyGet((WideString)L"ActiveSheet");

    // 重命名工作表:
    //sh.OlePropertySet("Name", "文件明细"); // 重命名当前工作簿
      if("" != WorkbooksName)
      {
        sh.OlePropertySet((WideString)L"Name", WorkbooksName); // 重命名当前工作簿
      }

    tExcelSumRow=sh.OlePropertyGet((WideString)L"Rows").OlePropertyGet((WideString)L"Count"); // 取得Excel文件可以使用的总行数,固定为65536
    tExcelSumCol=sh.OlePropertyGet((WideString)L"Columns").OlePropertyGet((WideString)L"Count"); // 取得Excel文件可以使用的总列数,固定为256
    return 0;
  }
//---------------------------------------------------------------------------
  void iCloseVariant( // 关闭Excel线程

  ){
    ex=Unassigned;
    newxls=Unassigned;
    sh=Unassigned;
    ex=NULL;
    newxls=NULL;
    sh=NULL;

    // 结束,如果没有如下代码,EXCEL线程直到应用程序退出才结束
    Variant Axl,Workbook,AxSheet,nms,bef,aft;
    Axl=Unassigned;
    Workbook=Unassigned;
    AxSheet=Unassigned;
    bef=Unassigned;
    aft=Unassigned;
    nms=Unassigned;
  }
//---------------------------------------------------------------------------
  int iStringGridToExcelW( // 通过OLE将DBGrid中的数据导出到Excel的自定义函数
    TStringGrid * StringGrid
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == StringGrid)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
    int tGridRow=StringGrid->RowCount; // StringGrid总共的行数
    int tGridCol=StringGrid->ColCount; // StringGrid总共的列数
     if(
       tGridRow<=0
       ||
       tGridCol<=0
     ){
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"行数或列数为0,没有可导出的数据"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                );
              }
            return -2;
     }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -3;
     }

    WideString str1; // 要入库的数据

      if(tGridRow>=tExcelSumRow)
      {
        tGridRow=tExcelSumRow-1;
      }

      if(tGridCol>=tExcelSumCol)
      {
        tGridRow=tExcelSumCol-1;
      }

    // 全部区域单元格格式设置
    str1=L"A1:"+ExcelRangeW[tGridCol-1]+IntToStr(tGridRow);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框

    sh.OlePropertyGet((WideString)"Range",str1).OlePropertySet((WideString)"NumberFormatLocal",(WideString)L"@"); // 设置指定单元格格式为“文本”
    // "@"前面必须使用(WideString)转换在WPS下才好用
    // WPS中如果L"@"前面不加(WideString)的话数字会显示为形如“Tru1900”的形式,双击单元格后变为“1900-1-2”等

    // 第一行格式设置
    str1=L"A1:"+ExcelRangeW[tGridCol]+L"1";
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",true); // 设置第一行区域中所有单元格的字体为粗体字
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"HorizontalAlignment",3); // 居中

    // 第一列格式设置
    str1=L"A1:A"+IntToStr(tGridRow);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",true); // 设置第一列区域中所有单元格的字体为粗体字

      for(int i=0;i<tGridRow;i++) // 行数
      {
          for(int j=0;j<tGridCol;j++) // 列数
          {
            str1=StringGrid->Cells[j][i];
            sh.OlePropertyGet((WideString)L"Cells",i+1,j+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
          }
      }
      //for(int i=0;i<tGridCol;i++){ // 按照StringGrid列宽度设置Excel中对应的列宽度
        //sh.OlePropertyGet((WideString)"Columns",i+1).OlePropertySet((WideString)"ColumnWidth",StringGrid->ColWidths[i]); // 设置指定区域所包含的所有列的列宽为28
      //}//设置后的宽度比StringGrid中的大

    iCloseVariant(); // 关闭Excel线程

    return 0;
  }

#7


接上面



//---------------------------------------------------------------------------
  int iTreeViewToExcelW( // 通过OLE将TreeView中的数据导出到Excel的自定义函数
    TTreeView * TView
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == TView)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
    int n=TView->Items->Count;
      if(n<=0)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"行数为0,没有可导出的数据"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                );
              }
            return -2;
      }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -3;
     }

    WideString str1; // 要入库的数据

    int z=0;
      for(int i=0;i<n;i++)
      {
        str1=TView->Items->Item[i]->Text;
          if(TView->Items->Item[i]->Level>z)
          {
            z=TView->Items->Item[i]->Level;
          }
        sh.OlePropertyGet((WideString)L"Cells",i+1,TView->Items->Item[i]->Level+1).OlePropertySet((WideString)L"NumberFormatLocal", (WideString)L"@"); // 设置指定列单元格格式为“文本”,"@"不能使用L
        sh.OlePropertyGet((WideString)L"Cells",i+1,TView->Items->Item[i]->Level+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
      }

    str1="A1:"+ExcelRangeW[z]+IntToStr(n);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框//BCB XE
    //sh.OlePropertyGet((WideString)"Range",("A1:"+ExcelRangeW[z]+IntToStr(n)).t_str()).OlePropertyGet((WideString)"Borders").OlePropertySet((WideString)"LineStyle",1); // 给指定单元格四周加上实线边框//BCB2010
    //sh.OlePropertyGet((WideString)"Range",("A1:"+ExcelRangeW[z]+IntToStr(n)).c_str()).OlePropertyGet((WideString)"Borders").OlePropertySet((WideString)"LineStyle",1); // 给指定单元格四周加上实线边框//BCB6 AND 2009
    //结束,如果没有如下代码,EXCEL线程直到应用程序退出才结束

    iCloseVariant(); // 关闭Excel线程

    return 0;
  }

#8


再接上面



//---------------------------------------------------------------------------
  int iDBGridToExcelW( // 通过OLE将DBGrid中的数据导出到Excel的自定义函数
    TDBGrid * Grid
    ,
    // false=列名字,true=列标题
    bool FieldName
    ,
    // Excel启动后是否可见,true=不可见,false=可见
    bool Visible
    ,
    // 是否停止刷新屏幕
    bool ScreenUpdating
    ,
    // 是否关闭Excel警告
    bool DisplayAlerts
    ,
    // 屏蔽大二进制文件
    bool Blob
    ,
    // 屏蔽长文本text字段
    bool Memo
    ,
    // 屏蔽格式化文本
    bool FmtMemo
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == Grid)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
      if(NULL == Grid->DataSource)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"DBGrid可能没有与DataSource关联"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -2; // DBGrid没有与DataSource关联
      }
      if(NULL == Grid->DataSource->DataSet)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"DBGrid可能没有与数据集关联"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -3; // 没有与数据集关联
      }

      if(false == Grid->DataSource->DataSet->Active)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"数据集没有开启"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -4; // 数据集没有开启
      }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -5;
     }

    WideString str1; // 要入库的数据
    int m=2; // 要写入数据的行号,最小值为1
    int n=Grid->FieldCount; // 列数

    str1=L"A1:"+ExcelRangeW[n-1]+L"1";
    //ShowMessage(("A1:"+iExcelRange[n-1]+"1").c_str());
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",(Variant)true);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"HorizontalAlignment",3); // 居中

    str1=L"A1:"+ExcelRangeW[n-1]+IntToStr(Grid->DataSource->DataSet->RecordCount+1);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"NumberFormatLocal",(WideString)L"@"); // 设置第一列单元格格式为“文本”

      for(int i=0;i<n;i++)
      {
          if(true == FieldName)
          {
            str1=Grid->Columns->Items[i]->Title->Caption; // 取得列标题
          }
          else
          {
            str1=Grid->Columns->Items[i]->FieldName; // 取得列名字
          }
          try
          {
            sh.OlePropertyGet((WideString)L"Cells",1,i+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
          }
          catch(...)
          {
            sh.OlePropertyGet((WideString)L"Application").OlePropertySet((WideString)L"ScreenUpdating",(Variant)true); // 停止刷新屏幕后必须这样恢复刷新才能看到单元格中的内容
            //Excel的警告提示:
            sh.OlePropertyGet((WideString)L"Application").OlePropertySet((WideString)L"DisplayAlerts",(Variant)true); // 打开Excel的警告提示,如提示保存等
            ex.OlePropertySet((WideString)L"Visible",(Variant)true); // 使Excel启动后可见

            iCloseVariant(); // 关闭Excel线程

              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"未知错误"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -6; // 数据集没有开启
          }
      }
    Grid->DataSource->DataSet->First(); // 返回首条
      while(!Grid->DataSource->DataSet->Eof)
      {
          for(int i=0;i<n;i++)
          {
              if(Blob==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftBlob)
              {
                continue; // 屏蔽大二进制文件字段,如image等字段
              }
              else
              if(Memo==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftMemo)
              {
                continue; // 屏蔽text(长文本字段,最大2G)字段
              }
              else
              if(Grid->Columns->Items[i]->Title->Column->Field->DataType == ftGraphic)
              {
                continue; // 屏蔽位图字段
              }
              else
              if(FmtMemo==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftFmtMemo)
              {
                continue; // 屏蔽格式化文本
              }


#9


该回复于2016-09-15 16:13:37被管理员删除

#1


BCB xe7 stringgrid 导入导出excelxe7还没用 ,,纠结 关注下 。。。。。

#2



function ExportStrGridToExcel(Args: array of const): Boolean;
var
  iCount, jCount: Integer;
  XLApp: Variant;
  Sheet: Variant;
  I: Integer;
begin
  Result := False;
  if not VarIsEmpty(XLApp) then
  begin
    XLApp.DisplayAlerts := False;
    XLApp.Quit;
    VarClear(XLApp);
  end;

  try
    XLApp := CreateOleObject('Excel.Application');
  except
    Exit;
  end;

  XLApp.WorkBooks.Add;
  XLApp.SheetsInNewWorkbook := High(Args) + 1;

  for I := Low(Args) to High(Args) do
  begin
    with TStringGrid(Args[I].VObject) do
    begin 
      XLApp.WorkBooks[1].WorkSheets[I+1].Name := Name;
      Sheet := XLApp.Workbooks[1].WorkSheets[Name];

      for jCount := 0 to RowCount - 1 do
      begin
        for iCount := 0 to ColCount - 1 do
        begin
          Sheet.Cells[jCount + 1, iCount + 1] := Cells[iCount, jCount];
        end;
      end;
    end;
  end;
  XlApp.Visible := True;  
end;




#3


ccrun的代码,供你参考
读取excel

void __fastcall TForm1::Button4Click(TObject *Sender)
{
StringGrid1->Cells[0][0]="序号";
StringGrid1->Cells[1][0]="交易码";
StringGrid1->Cells[2][0]="开始时间";
StringGrid1->Cells[3][0]="内容";
StringGrid1->Cells[4][0]="金 额";
StringGrid1->Cells[5][0]="号码";
int i=0;
StringGrid1->RowCount=2;
ADOQuery1->Open();
while(!ADOQuery1->Eof)
    {
        i++;
        StringGrid1->Cells[0][i]=ADOQuery1->FieldByName("序号")->AsInteger;
        StringGrid1->Cells[1][i]=ADOQuery1->FieldByName("交易码")->AsString;
        StringGrid1->Cells[2][i]=ADOQuery1->FieldByName("开始时间")->AsString;
        StringGrid1->Cells[3][i]=ADOQuery1->FieldByName("内容")->AsString;
        StringGrid1->Cells[4][i]=ADOQuery1->FieldByName("金 额")->AsInteger;
        StringGrid1->Cells[5][i]=ADOQuery1->FieldByName("号码")->AsString;
        ADOQuery1->Next();
        StringGrid1->RowCount++;
    }
ADOQuery1->Close();        
}
//---------------------------------------------------------------------------


导出excel

//---------------------------------------------------------------------------
#include<Comobj.hpp>
#include<Utilcls.h>

//---------------------------------------------------------------------------
void __fastcall  TForm1::SaveToExcel(char * FileName)
{
Variant ex,wk,sht,Range; //ole万能变量,定义excel对象使用
int FieldType[10]={0,0,0,0,2,0,0,0};
try{
 ex=CreateOleObject("Excel.Application"); //启动Excel
 wk=ex.OlePropertyGet("ActiveWorkBook");//创建工作簿对象
 ex.OlePropertyGet("WorkBooks").OleFunction("Add");//添加一个工作薄
 sht=ex.OlePropertyGet("ActiveSheet");//创建工作区
 }
 catch(...)
 {
  MessageDlg("无法启动Excel,可能尚未安装或文件已经损坏!",mtError,TMsgDlgButtons()<<mbYes,0);
  return;
 }


 int iSRow=0;
 int iSCol=0;

 char *cRange;
 cRange=CountCol("A1:", StringGrid1->ColCount - iSCol, 1);

 Range = sht.OlePropertyGet("Range",cRange);
 Range.OleFunction("Merge", false);
 //Range.OlePropertySet("VerticalAlignment", Edit1->Text.ToInt());//居中
 Range.OlePropertySet("HorizontalAlignment",3);//居中
 Range.OlePropertyGet("Interior").OlePropertySet("ColorIndex",24);
 Range .OlePropertyGet("Borders",1).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",2).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",3).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",4).OlePropertySet("LineStyle",1);

 ex.OlePropertySet("Caption","查询结果转入EXCEL:");
 ex.OlePropertySet("StatusBar","       【SQL TOOLS】 WGHSoft.ICBC   Tel:0571-87924880  Email: wghsoft@126.com");
 sht.OlePropertySet("Name", "核对单");
 sht.OlePropertyGet("Cells",1,1).OlePropertySet("Value","测 试 EXCEL");
 sht.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Name","华文中宋");
 sht.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Size",28);

 int i=2;

 for(int row=iSRow;row<StringGrid1->RowCount;row++,i++)
        for(int j=1, col=iSCol;col<StringGrid1->ColCount;col++,j++){
                if(i==2) ex.OlePropertyGet("Cells",j).OlePropertySet("ColumnWidth", StringGrid1->ColWidths[j-1]/7); //宽
                if(i%2==0)
                        sht.OlePropertyGet("Cells",i,j).OlePropertyGet("Interior").OlePropertySet("Color",RGB(213,251,206));
                        else
                        sht.OlePropertyGet("Cells",i,j).OlePropertyGet("Interior").OlePropertySet("Color",RGB(188,244,254));

                        switch(FieldType[col-1]){
                                case 2:
                                        if(BigData(StringGrid1->Cells[col][row].c_str()))
                                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("NumberFormatLocal","@");
                                        break;
                                default:
                                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("NumberFormatLocal","@");
                                        break;
                                }
                        sht.OlePropertyGet("Cells",i, j).OlePropertySet("Value", Trim(StringGrid1->Cells[col][row]).c_str());
                      }

 cRange=CountCol("A2:", StringGrid1->ColCount - iSCol, i-1);

 Range = sht.OlePropertyGet("Range", cRange);
 Range .OleProcedure("Select");
 Range .OlePropertyGet("Borders",1).OlePropertySet("LineStyle",1);//边框
 Range .OlePropertyGet("Borders",2).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",3).OlePropertySet("LineStyle",1);
 Range .OlePropertyGet("Borders",4).OlePropertySet("LineStyle",1);

 Range .OlePropertySet("RowHeight", 20); //行高

 sht.OleFunction("SaveAs",FileName);  //表格保存

 ex.OlePropertySet("Visible",(Variant)true); //使Excel可见

}

//----------------------------------------------

快速导出excel

String RemoveExtendName(String sFileName)//去除后缀
{
String dFileName;

if(sFileName.Pos("."))
        dFileName=sFileName.SubString(1,sFileName.Pos(".")-1);
                else dFileName=sFileName;
return  dFileName;
}

//----------------------------------------------------------
void __fastcall TForm1::Button5Click(TObject *Sender)
{
String FileName=RemoveExtendName("c:/wsj.htm");
ToHtml(StringGrid1, FileName.c_str(),"测试 StringGrid to Excel");
}


//---------------------------------------------------------------------------

#4


我以前写过的OLE相关代码,有一些瑕疵的。目前在我自己用的库中,支持从ListView/StringGrid/DBGrid等控件中导入/导出到Excel/Csv/Word等格式,已经修正很多问题。

#5


引用 4 楼 ccrun 的回复:
我以前写过的OLE相关代码,有一些瑕疵的。目前在我自己用的库中,支持从ListView/StringGrid/DBGrid等控件中导入/导出到Excel/Csv/Word等格式,已经修正很多问题。

BCB xe7 stringgrid 导入导出excel
能分享一下吗?

#6


我在05年时写过一个将StringGrid、TreeView或DBGrid控件中的数据导出到Excel或WPS表格的函数集,2011年01月完善到XE,目前完美支持XE全系列

iExcelToolsW.cpp



  #include "iExcelToolsW.h" // 一组数据导出到Excel的工具集

//  #include "iExcelToolsW.cpp" // 一组数据导出到Excel的工具集

#ifndef _iExcelToolsW_cpp_
#define _iExcelToolsW_cpp_

/*
  一个将StringGrid、TreeView或DBGrid控件中的数据导出到Excel或WPS表格的函数集
  www.plm.hk 编写于2005年09月,最后修改于2011年01月
*/

  WideString ExcelRangeW[256]=
  {
    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
    "AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ",
    "BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ",
    "CA","CB","CC","CD","CE","CF","CG","CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ",
    "DA","DB","DC","DD","DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ",
    "EA","EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ",
    "FA","FB","FC","FD","FE","FF","FG","FH","FI","FJ","FK","FL","FM","FN","FO","FP","FQ","FR","FS","FT","FU","FV","FW","FX","FY","FZ",
    "GA","GB","GC","GD","GE","GF","GG","GH","GI","GJ","GK","GL","GM","GN","GO","GP","GQ","GR","GS","GT","GU","GV","GW","GX","GY","GZ",
    "HA","HB","HC","HD","HE","HF","HG","HH","HI","HJ","HK","HL","HM","HN","HO","HP","HQ","HR","HS","HT","HU","HV","HW","HX","HY","HZ",
    "IA","IB","IC","ID","IE","IF","IG","IH","II","IJ","IK","IL","IM","IN","IO","IP","IQ","IR","IS","IT","IU","IV"
  };
  Variant ex,newxls,sh;
  int tExcelSumRow=0; // 取得Excel文件可以使用的总行数,固定为65536
  int tExcelSumCol=0; // 取得Excel文件可以使用的总列数,固定为256
//---------------------------------------------------------------------------
  int iStartupExcel( // 启动Excel
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      try
      {
        ex=Variant::CreateObject((WideString)L"Excel.Application"); // 启动Excel
        //ex=Variant::CreateObject((WideString)L"et.Application"); // 如果没有安装Excel就使用WPS表格
      }
      //catch(...)
      //catch(Exception &e)
      catch(Sysutils::Exception &T_MFWV)
      {
          try
          {
            //ex=Variant::CreateObject((WideString)L"Excel.Application"); // 启动Excel
            ex=Variant::CreateObject((WideString)L"et.Application"); // 如果没有安装Excel就使用WPS表格
          }
          //catch(...)
          //catch(Exception &e)
          catch(Sysutils::Exception &T_VWLK)
          {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  (
                    T_MFWV.Message+"\r\n"+T_VWLK.Message+L"\r\n发生意外!"
                  ).w_str()
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
          }
      }
    ex.OlePropertySet((WideString)L"Visible",(Variant)true); // 使Excel启动后可见
    //ex.OlePropertySet("Visible",(Variant)false); // 使Excel启动后不可见
    newxls=(ex.OlePropertyGet((WideString)L"Workbooks")).OleFunction((WideString)L"Add"); // 使用ExcelApp的Exec方法新建一新工作薄
    sh=newxls.OlePropertyGet((WideString)L"ActiveSheet");

    // 重命名工作表:
    //sh.OlePropertySet("Name", "文件明细"); // 重命名当前工作簿
      if("" != WorkbooksName)
      {
        sh.OlePropertySet((WideString)L"Name", WorkbooksName); // 重命名当前工作簿
      }

    tExcelSumRow=sh.OlePropertyGet((WideString)L"Rows").OlePropertyGet((WideString)L"Count"); // 取得Excel文件可以使用的总行数,固定为65536
    tExcelSumCol=sh.OlePropertyGet((WideString)L"Columns").OlePropertyGet((WideString)L"Count"); // 取得Excel文件可以使用的总列数,固定为256
    return 0;
  }
//---------------------------------------------------------------------------
  void iCloseVariant( // 关闭Excel线程

  ){
    ex=Unassigned;
    newxls=Unassigned;
    sh=Unassigned;
    ex=NULL;
    newxls=NULL;
    sh=NULL;

    // 结束,如果没有如下代码,EXCEL线程直到应用程序退出才结束
    Variant Axl,Workbook,AxSheet,nms,bef,aft;
    Axl=Unassigned;
    Workbook=Unassigned;
    AxSheet=Unassigned;
    bef=Unassigned;
    aft=Unassigned;
    nms=Unassigned;
  }
//---------------------------------------------------------------------------
  int iStringGridToExcelW( // 通过OLE将DBGrid中的数据导出到Excel的自定义函数
    TStringGrid * StringGrid
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == StringGrid)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
    int tGridRow=StringGrid->RowCount; // StringGrid总共的行数
    int tGridCol=StringGrid->ColCount; // StringGrid总共的列数
     if(
       tGridRow<=0
       ||
       tGridCol<=0
     ){
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"行数或列数为0,没有可导出的数据"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                );
              }
            return -2;
     }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -3;
     }

    WideString str1; // 要入库的数据

      if(tGridRow>=tExcelSumRow)
      {
        tGridRow=tExcelSumRow-1;
      }

      if(tGridCol>=tExcelSumCol)
      {
        tGridRow=tExcelSumCol-1;
      }

    // 全部区域单元格格式设置
    str1=L"A1:"+ExcelRangeW[tGridCol-1]+IntToStr(tGridRow);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框

    sh.OlePropertyGet((WideString)"Range",str1).OlePropertySet((WideString)"NumberFormatLocal",(WideString)L"@"); // 设置指定单元格格式为“文本”
    // "@"前面必须使用(WideString)转换在WPS下才好用
    // WPS中如果L"@"前面不加(WideString)的话数字会显示为形如“Tru1900”的形式,双击单元格后变为“1900-1-2”等

    // 第一行格式设置
    str1=L"A1:"+ExcelRangeW[tGridCol]+L"1";
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",true); // 设置第一行区域中所有单元格的字体为粗体字
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"HorizontalAlignment",3); // 居中

    // 第一列格式设置
    str1=L"A1:A"+IntToStr(tGridRow);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",true); // 设置第一列区域中所有单元格的字体为粗体字

      for(int i=0;i<tGridRow;i++) // 行数
      {
          for(int j=0;j<tGridCol;j++) // 列数
          {
            str1=StringGrid->Cells[j][i];
            sh.OlePropertyGet((WideString)L"Cells",i+1,j+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
          }
      }
      //for(int i=0;i<tGridCol;i++){ // 按照StringGrid列宽度设置Excel中对应的列宽度
        //sh.OlePropertyGet((WideString)"Columns",i+1).OlePropertySet((WideString)"ColumnWidth",StringGrid->ColWidths[i]); // 设置指定区域所包含的所有列的列宽为28
      //}//设置后的宽度比StringGrid中的大

    iCloseVariant(); // 关闭Excel线程

    return 0;
  }

#7


接上面



//---------------------------------------------------------------------------
  int iTreeViewToExcelW( // 通过OLE将TreeView中的数据导出到Excel的自定义函数
    TTreeView * TView
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == TView)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
    int n=TView->Items->Count;
      if(n<=0)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"行数为0,没有可导出的数据"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                );
              }
            return -2;
      }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -3;
     }

    WideString str1; // 要入库的数据

    int z=0;
      for(int i=0;i<n;i++)
      {
        str1=TView->Items->Item[i]->Text;
          if(TView->Items->Item[i]->Level>z)
          {
            z=TView->Items->Item[i]->Level;
          }
        sh.OlePropertyGet((WideString)L"Cells",i+1,TView->Items->Item[i]->Level+1).OlePropertySet((WideString)L"NumberFormatLocal", (WideString)L"@"); // 设置指定列单元格格式为“文本”,"@"不能使用L
        sh.OlePropertyGet((WideString)L"Cells",i+1,TView->Items->Item[i]->Level+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
      }

    str1="A1:"+ExcelRangeW[z]+IntToStr(n);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框//BCB XE
    //sh.OlePropertyGet((WideString)"Range",("A1:"+ExcelRangeW[z]+IntToStr(n)).t_str()).OlePropertyGet((WideString)"Borders").OlePropertySet((WideString)"LineStyle",1); // 给指定单元格四周加上实线边框//BCB2010
    //sh.OlePropertyGet((WideString)"Range",("A1:"+ExcelRangeW[z]+IntToStr(n)).c_str()).OlePropertyGet((WideString)"Borders").OlePropertySet((WideString)"LineStyle",1); // 给指定单元格四周加上实线边框//BCB6 AND 2009
    //结束,如果没有如下代码,EXCEL线程直到应用程序退出才结束

    iCloseVariant(); // 关闭Excel线程

    return 0;
  }

#8


再接上面



//---------------------------------------------------------------------------
  int iDBGridToExcelW( // 通过OLE将DBGrid中的数据导出到Excel的自定义函数
    TDBGrid * Grid
    ,
    // false=列名字,true=列标题
    bool FieldName
    ,
    // Excel启动后是否可见,true=不可见,false=可见
    bool Visible
    ,
    // 是否停止刷新屏幕
    bool ScreenUpdating
    ,
    // 是否关闭Excel警告
    bool DisplayAlerts
    ,
    // 屏蔽大二进制文件
    bool Blob
    ,
    // 屏蔽长文本text字段
    bool Memo
    ,
    // 屏蔽格式化文本
    bool FmtMemo
    ,
    // 重命名工作簿
    WideString WorkbooksName
    ,
    // 如果出错是否弹出错误提示框
    bool T_OSZE
  ){
      if(NULL == Grid)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"控件不能为NULL"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -1;
      }
      if(NULL == Grid->DataSource)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"DBGrid可能没有与DataSource关联"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL // 在对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -2; // DBGrid没有与DataSource关联
      }
      if(NULL == Grid->DataSource->DataSet)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"DBGrid可能没有与数据集关联"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -3; // 没有与数据集关联
      }

      if(false == Grid->DataSource->DataSet->Active)
      {
              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"数据集没有开启"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -4; // 数据集没有开启
      }
     if(
       iStartupExcel( // 启动Excel
         // 重命名工作簿
         WorkbooksName
         ,
         // 如果出错是否弹出错误提示框
         T_OSZE
       )!=0
     ){
       // 此处在Excel的启动函数中已经有提示框
            return -5;
     }

    WideString str1; // 要入库的数据
    int m=2; // 要写入数据的行号,最小值为1
    int n=Grid->FieldCount; // 列数

    str1=L"A1:"+ExcelRangeW[n-1]+L"1";
    //ShowMessage(("A1:"+iExcelRange[n-1]+"1").c_str());
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Font").OlePropertySet((WideString)L"Bold",(Variant)true);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"HorizontalAlignment",3); // 居中

    str1=L"A1:"+ExcelRangeW[n-1]+IntToStr(Grid->DataSource->DataSet->RecordCount+1);
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertyGet((WideString)L"Borders").OlePropertySet((WideString)L"LineStyle",1); // 给指定单元格四周加上实线边框
    sh.OlePropertyGet((WideString)L"Range",str1).OlePropertySet((WideString)L"NumberFormatLocal",(WideString)L"@"); // 设置第一列单元格格式为“文本”

      for(int i=0;i<n;i++)
      {
          if(true == FieldName)
          {
            str1=Grid->Columns->Items[i]->Title->Caption; // 取得列标题
          }
          else
          {
            str1=Grid->Columns->Items[i]->FieldName; // 取得列名字
          }
          try
          {
            sh.OlePropertyGet((WideString)L"Cells",1,i+1).OlePropertySet((WideString)L"Value",str1); // 将字符写入指定单元格
          }
          catch(...)
          {
            sh.OlePropertyGet((WideString)L"Application").OlePropertySet((WideString)L"ScreenUpdating",(Variant)true); // 停止刷新屏幕后必须这样恢复刷新才能看到单元格中的内容
            //Excel的警告提示:
            sh.OlePropertyGet((WideString)L"Application").OlePropertySet((WideString)L"DisplayAlerts",(Variant)true); // 打开Excel的警告提示,如提示保存等
            ex.OlePropertySet((WideString)L"Visible",(Variant)true); // 使Excel启动后可见

            iCloseVariant(); // 关闭Excel线程

              if(true == T_OSZE) // 如果出错是否弹出错误提示框
              {
                Application->BringToFront(); // 将应用程序置于激活状态并且拥有焦点
                MessageBox(
                  NULL
                  ,
                  L"未知错误"
                  ,
                  L"系统提示"
                  ,
                  MB_OK|MB_ICONERROR // 一个确定按钮和一个红叉图标
                  //MB_OK|MB_ICONSTOP // 一个红叉图标
                  //MB_OK|MB_ICONHAND // 一个红叉图标
                  //MB_OK|MB_SYSTEMMODAL// 在 对话框的标题栏上加上windows标志
                  //MB_OK|MB_ICONQUESTION // 一个问号图标
                  //MB_OK|MB_ICONEXCLAMATION // 一个黄三角的“!”号图标
                  //MB_OK|MB_ICONASTERISK // 一个语言框的“!”号图标
                  //MB_OK|MB_USERICON // 没有图标,但留出了图标位置
                  //MB_OK // 没有图标,没有留出图标位置
                );
              }
            return -6; // 数据集没有开启
          }
      }
    Grid->DataSource->DataSet->First(); // 返回首条
      while(!Grid->DataSource->DataSet->Eof)
      {
          for(int i=0;i<n;i++)
          {
              if(Blob==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftBlob)
              {
                continue; // 屏蔽大二进制文件字段,如image等字段
              }
              else
              if(Memo==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftMemo)
              {
                continue; // 屏蔽text(长文本字段,最大2G)字段
              }
              else
              if(Grid->Columns->Items[i]->Title->Column->Field->DataType == ftGraphic)
              {
                continue; // 屏蔽位图字段
              }
              else
              if(FmtMemo==true && Grid->Columns->Items[i]->Title->Column->Field->DataType == ftFmtMemo)
              {
                continue; // 屏蔽格式化文本
              }


#9


该回复于2016-09-15 16:13:37被管理员删除