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
// Error ?
end;
finally
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if SaveAsExcelFile(stringGrid1, 'c:\MyExcelFile.xls') then
ShowMessage('stringGrid saved!');
end;
{*************************************************}
// Reiner Schlay http://www.assu-assist.nl/
function RefToCell(ARow, ACol: Integer): string;
begin
Result := Chr(Ord('A') + ACol - 1) + i2s(ARow);
end;
procedure StringGridToExcel(AGrid: TstringGrid);
var
i, j: Integer;
Excel: Application_;
Book: Workbook;
Sheet: _WorkSheet;
Data: OLEVariant;
begin
Data := VarArrayCreate([1, AGrid.RowCount, 1, AGrid.ColCount],
varVariant);
for i := 0 to AGrid.ColCount - 1 do
for j := 0 to AGrid.RowCount - 1 do
Data[j + 1, i + 1] := AGrid.Cells[i, j];
Excel := CoApplication_.Create;
Book := Excel.WorkBooks.Add(EmptyParam, 0);
Sheet := Excel.Sheets.Add(EmptyParam, EmptyParam, 1,
xlWorksheet, 0) as _WorkSheet;
Sheet.Range[RefToCell(1, 1), RefToCell(AGrid.RowCount,
AGrid.ColCount)].Value := Data;
Excel.Visible[0] := True;
Excel.UserControl := True;
end;
|