program project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, sysutils, fpstypes, fpSpreadsheet, laz_fpspreadsheet;
type TDynFloat = array of array of Real;
var
MyWorkbook: TsWorkbook;
MyWorksheet: TsWorksheet;
myReturnedArray : TDynFloat;
function ReadSpreadsheetRange
(MyWorksheet: TsWorksheet; startCell : string; endCell: string = '')
: TDynFloat;
// Function reads numbers FROM range of cells (startCell : endCell)
// and RETURNS them as a dynamical array of Floats.
// If endCell is not provided, it reads all cells from startCell to the last.
// Example usage:
// ReadSpreadsheetRange(MyWorksheet,'B2', 'F3')
var
LastColumn, LastRow, row, col : integer;
cell : PCell;
myArray : TDynFloat;
begin
if MyWorksheet.FindCell(startCell) = nil then
begin
// ToDo: Maybe I should return an empty array before exit (???)
WriteLn('Cell ' + startCell + ' does not exist in ' + MyWorksheet.Name);
exit;
end;
cell := MyWorksheet.FindCell(startCell);
// Set last column and rows depending on whether endCell provided
if ( endCell = '' ) or ( MyWorksheet.FindCell(endCell) = nil ) then
begin
LastColumn := MyWorksheet.GetLastColIndex();
LastRow := MyWorksheet.GetLastRowIndex();
end
else
begin
LastColumn := MyWorksheet.FindCell(endCell)^.Col;
LastRow := MyWorksheet.FindCell(endCell)^.Row;
end;
SetLength(myArray,LastRow - cell^.Row + 1,LastColumn - cell^.Col + 1);
for row := cell^.Row to LastRow do
for col := cell^.Col to LastColumn do
begin
myArray[row - cell^.Row, col - cell^.Col] :=
MyWorksheet.ReadAsNumber(row,col);
end;
Result := myArray;
end;
begin
////////////////////////////////
// Read worksheet;
MyWorkbook := TsWorkbook.Create;
MyWorkbook.ReadFromFile('testData.xls');
MyWorksheet := MyWorkbook.GetWorksheetByIndex(0);
///////////////////////////////
//////////////////////////////
// Use function above and test it
myReturnedArray := ReadSpreadsheetRange(MyWorksheet,'B2');
WriteLn('Size of the returned array is: ' +
FloatToStr(Length(myReturnedArray)));
// value in this cell (C2): 42,4842
WriteLn(myReturnedArray[0,1]);
// value in this cell (D2): 45
WriteLn(myReturnedArray[0,2]);
// value in this cell (E2): THIS IS NOT A NUMBER
WriteLn(myReturnedArray[0,3]);
MyWorkbook.Free;
ReadLn;
end.