Recent

Author Topic: get last worksheet from Excel  (Read 2518 times)

Hansvb

  • Hero Member
  • *****
  • Posts: 619
get last worksheet from Excel
« on: June 26, 2016, 10:10:44 pm »
How can i get the last sheet from a Excel workbook and then add 1 sheet and write into the new sheet?

i know how to create a workbook end how to write to a sheet.


wp

  • Hero Member
  • *****
  • Posts: 11923
Re: get last worksheet from Excel
« Reply #1 on: June 26, 2016, 10:56:51 pm »
Code: Pascal  [Select][+][-]
  1. var
  2.   book: TsWorkbook;
  3.   sheet: TsWorksheet;
  4. begin
  5.   // Create workbook structure
  6.   book := TsWorkbook.Create;
  7.   // Load Excel file
  8.   book.LoadFromFile('Excelfile.xls');
  9.   // Delete all sheets but the last one
  10.   for i:=book.GetWorksheetCount - 2 downto 0 do
  11.   begin
  12.     sheet := book.GetWorksheetByIndex(i);
  13.     book.RemoveWorksheet(sheet);
  14.   end;
  15.   // Add new sheet
  16.   sheet := book.AddWorksheet('New sheet');
  17.   // Write something to the new sheet
  18.   sheet.WriteNumber(0, 0, 1.234);
  19.   // Save resulting workbook
  20.   book.WriteToFile('NewFile.xls');
  21.   // Clean up
  22.   book.Free;
  23. end;

Hansvb

  • Hero Member
  • *****
  • Posts: 619
Re: get last worksheet from Excel
« Reply #2 on: June 27, 2016, 07:47:17 pm »
Found my  mistake. I created 2 Excel objects.

I tried to save the Excel file with
Code: Pascal  [Select][+][-]
  1. book.WriteToFile('NewFile.xls');
But then i get a warning:
Method writetofile is not supported by automation object.

Found it too. It should be:
Code: Pascal  [Select][+][-]
  1. book.saveas(widestring(SaveDialog_FileName));

The difference is that use ole automation. And the example from WP is made with fspreadsheet.
« Last Edit: June 27, 2016, 09:02:41 pm by Hansvb »

 

TinyPortal © 2005-2018