问题描述:delphi操作Excel,在delphi中把StringGrid中的内容导出到Excel中,这段代码能正常运行,但是好多知识点我不懂,
比如程序中的DisplayAlerts、Quit、WorkBooks、SheetsInNewWorkbook等,还有对二维数组求LOW和High是什么值,譬如:Low(Args),
请大家帮忙解释,这要看哪方面的知识呢,是VBA吗?并说说delphi操作Excel、Word的原理或方法。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;

解决方案 »

  1.   

    我博客里有用接口方法的,不用variant
      

  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  // 测试变体是否为UNASSIGNED
      begin
        XLApp.DisplayAlerts := False;//boolean类型,如果是true(缺省值),Excel在你代码运行时,在必要时候会显示警告信息:比如删除一个表单的时候。将该值设置为false将跳过这些警告。Excel会认为你选择了每个警告中的缺省返回值。
        XLApp.Quit;//调用Quit方法
        VarClear(XLApp); //清除XLApp变体
      end;
      try
        XLApp := CreateOleObject('Excel.Application');
      except
        Exit;
    end;XLApp.WorkBooks.Add; //添加返回所有打开的工作簿的引用的集合。XLApp.SheetsInNewWorkbook := High(Args) + 1; //定义一个BOOK中有多少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 // 数据导出到excel             
             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;