3

这是我生成 Excel 2007 XLSX 文件的小测试应用程序:

uses
  Excel2007;

function CreateExportExcelWorkbook(AApp: ExcelApplication; ALCID: Integer): ExcelWorkbook;
var
  OldDefaultSaveFormat: XlFileFormat;
begin
  OldDefaultSaveFormat := AApp.DefaultSaveFormat;
  AApp.DefaultSaveFormat := xlOpenXMLWorkbook;
  try
    Result := AApp.Workbooks.Add(xlWBATWorksheet, ALCID);
  finally
    AApp.DefaultSaveFormat := OldDefaultSaveFormat;
  end;
end;

procedure FixTopRows(AApp: ExcelApplication; ARowCount: Integer);
var
  ActiveWindow: Window;
begin
  ActiveWindow := AApp.ActiveWindow;
  ActiveWindow.SplitColumn := 0;
  ActiveWindow.SplitRow := ARowCount;
  ActiveWindow.FreezePanes := True;
end;

procedure TForm1.Button1Click(Sender: TObject);
const
  cRowCount = 200;
  cColCount = 10;
var
  LCID: Integer;
  ExcelApp: ExcelApplication;
  Workbook: ExcelWorkbook;
  Worksheet: ExcelWorksheet;
  i, j: Integer;
  FVarArray: Variant;
  Cell1, Range: ExcelRange;
begin
  LCID := GetUserDefaultLCID;

  ExcelApp := CoExcelApplication.Create;
  try
    ExcelApp.Visible[LCID] := False;
    ExcelApp.UserControl := False;
    ExcelApp.DisplayAlerts[LCID] := False;

    Workbook := CreateExportExcelWorkbook(ExcelApp, LCID);
    Worksheet := Workbook.Worksheets.Item[1] as ExcelWorksheet;

    FVarArray := VarArrayCreate([0, cRowCount - 1, 0, cColCount - 1], varVariant);

    for j := 0 to cColCount - 1 do
      FVarArray[0, j] := Format('Column %d', [j]);


    for i := 1 to cRowCount - 1 do
      for j := 0 to cColCount - 1 do
        FVarArray[i, j] := 100 * i + j;

    Cell1 := Worksheet.Cells.Range['A1', 'A1'];
    Range := Worksheet.Range[Cell1, Cell1.Offset[cRowCount - 1, cColCount - 1]];
    Range.Value[EmptyParam] := FVarArray;
    VarClear(FVarArray);
    Range.EntireColumn.AutoFit;

    FixTopRows(ExcelApp, 1);

    Range := Worksheet.Range[Cell1, Cell1.Offset[0, cColCount - 1]];
    //Range := Cell1.EntireRow;
    //Range.AutoFilter(1, 'All', EmptyParam, EmptyParam, True);

    Workbook.SaveAs(ExpandFileName('test.xlsx'), EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
      xlNoChange, EmptyParam, False, EmptyParam, EmptyParam, EmptyParam, LCID);
  finally
    ExcelApp.Quit;
  end;
end;

UnitExcel2007是导入的 Excel 2007 类型库。到目前为止,这工作正常。但是,我想像此屏幕截图中那样自动过滤标题行:自动筛选的屏幕截图 不幸的是,我通过 OLE 自动化执行此操作的所有尝试都导致了 OLE 或 Variant 异常。知道我应该如何进行吗?

注意:数据不应该被过滤——我只想要下拉按钮。

4

1 回答 1

3

您需要指定您未能执行的操作员。例如:

Worksheet.Cells.AutoFilter(1, EmptyParam, xlAnd, EmptyParam, True);

请注意,该Criteria1参数是可选的,可以省略,默认为'All'.

于 2013-09-03T10:35:28.663 回答