问题
I am developing an application that need to generate excel sheets. How do we append rows to an existing excel sheet? I am using Delphi 2007.(and I am using SM Software TXLS... components...but I am ok with answers in native delphi excel components). Thanking you all, Pradeep
回答1:
Over the years, I've found Deborah Pate's site has helped me by providing useful code samples: http://www.djpate.freeserve.co.uk/AutoExcl.htm. We use the CreateOleObject approach.
回答2:
Normally you won't need to append rows, because you can just reference any cell to write in it. You may need to insert rows in the middle of your sheet like this:
ExcelApplication.ActiveSheet.Rows[10].Insert;
or
ExcelApplication.ActiveSheet.ActiveCell.EntireRow.Insert;
If you develop for Excel, I think it is more convenient to use TExcelApplication because it is just a wrapper around the type library. You can use the source code of the imported type library as a reference. Another helpful tool is the macro recording in Excel itself. The VBA code created by recording a macro can easily be translated into Delphi code. Sometimes you need to do little changes or improvements, but it is still a lot of help when you are stuck.
回答3:
Hier some untested sample code you can use to insert data to Excel:
var
Cols: integer;
Rows: integer;
Excel, XLSheet: Variant;
failure: Integer;
begin
failure:=0;
try
Excel:=CreateOleObject('Excel.Application');
except
failure:=1;
end;
if failure = 0 then
begin
Excel.Visible:=False;
Excel.WorkBooks.Open(<Excell_Filename>);
XLSheet := Excel.Worksheets[1];
Cols := XLSheet.UsedRange.Columns.Count;
Rows := XLSheet.UsedRange.Rows.Count;
//Insert Data
Excel.Cells[1, 1].Value := 'SwissDelphiCenter.ch';
Excel.Cells[2, 1].Value := 'http://www.swissdelphicenter.ch';
Excel.Cells[3, 1].Value := FormatDateTime('dd-mmm-yyyy', Now);
Excel.Range['A2', 'D2'].Value := VarArrayOf([1, 10, 100, 1000]);
// Save the Workbook
Excel.SaveAs(Excell_Filename);
Excel.Workbooks.Close;
Excel.Quit;
Excel:=Unassigned;
end;
end;
来源:https://stackoverflow.com/questions/5114484/how-to-append-rows-to-an-excel-sheet