StringGrid存储为Excel文档

function SaveAsExcelFile(StringGrid: TStringGrid; FileName: string):
boolean;
const
  xlWBATWorksheet = -4167;
var
  Row, Col:     integer;
  GridPrevFile: string;
  XLApp, Sheet: OLEVariant;
begin
  Result := false;
  XLApp := CreateOleObject('Excel.Application');
  try
    XLApp.Visible := False;
    XLApp.Workbooks.Add(xlWBatWorkSheet);
    Sheet      := XLApp.Workbooks[1].WorkSheets[1];
    Sheet.Name := 'My Sheet Name';
    for col := 0 to StringGrid.ColCount - 1 do
      for row := 0 to StringGrid.RowCount - 1 do
        Sheet.Cells[row + 1,col + 1] := StringGrid.Cells[col, row];
    try
      XLApp.Workbooks[1].SaveAs(FileName);
      Result := True;
    except
    end;
  finally
    if not VarIsEmpty(XLApp) then
    begin
      XLApp.DisplayAlerts := False;
      XLApp.Quit;
      XLAPP := Unassigned;
      Sheet := Unassigned;
    end;
  end;
end;
posted @ 2008-07-18 16:27  delphi中间件  阅读(397)  评论(0编辑  收藏  举报