// --> SAVE StringGrid TO XLSX
procedure SAVEStringGridXLSX(StringGrid1: TStringGrid);
const
HEADER_FONT_SIZE = 11; // in Points
DEFAULT_FONT_SIZE = 13; // in Points
NICE_ROWHEIGHT_FACTOR = 1.5; // adds extra margin to the cell
var
WORKBOOK: TsWorkbook;
WORKSHEET: TsWorksheet;
CELL: pCell;
Row: Integer; // Row
Col: Integer; // Column
tmpvalue: Single;
begin
Workbook := TsWorkbook.Create;
try
// Add a worksheet to the workbook
Worksheet := Workbook.AddWorksheet('Export from grid');
// Set default font for the workbook
Workbook.SetDefaultFont('Dejavu Sans Mono', DEFAULT_FONT_SIZE);
Worksheet.WriteDefaultRowHeight(DEFAULT_FONT_SIZE * NICE_ROWHEIGHT_FACTOR,
suPoints);
// Set default column widths based on StringGrid column sizes
for Col := 0 to StringGrid1.ColCount - 1 do
Worksheet.WriteColWidth(Col, pxToPts(StringGrid1.ColWidths[Col],
Screen.PixelsPerInch), suPoints);
// Configure the header row
for Col := 0 to StringGrid1.ColCount - 1 do
begin
// Write header text
Cell := Worksheet.WriteText(0, Col, StringGrid1.Cells[Col, 0]);
Worksheet.WriteHorAlignment(Cell, haCenter); // Center horizontally
Worksheet.WriteVertAlignment(Cell, vaCenter); // Center vertically
Worksheet.WriteBorders(Cell, [cbNorth, cbSouth, cbEast, cbWest]); // Add borders
Worksheet.WriteFontStyle(Cell, [fssBold]); // Bold font
Worksheet.WriteFontSize(Cell, HEADER_FONT_SIZE); // Set font size
Worksheet.WriteFontName(Cell, 'Dejavu Sans Mono'); // Set font name
Worksheet.WriteBackgroundColor(Cell, scYellow); // Set background color
end;
// Adjust the height for the header row
Worksheet.WriteRowHeight(0, HEADER_FONT_SIZE * NICE_ROWHEIGHT_FACTOR,
suPoints);
// Write data cells
for Row := 1 to StringGrid1.RowCount - 1 do
begin
for Col := 0 to StringGrid1.ColCount - 1 do
begin
// Check if cell contains a number
if TryStrToFloat(StringGrid1.Cells[Col, Row], TmpValue) then
Cell := Worksheet.WriteNumber(Row, Col, TmpValue)
else
Cell := Worksheet.WriteText(Row, Col, StringGrid1.Cells[Col, Row]);
// Add borders and center text
Worksheet.WriteBorders(Cell, [cbNorth, cbSouth, cbEast, cbWest]);
Worksheet.WriteHorAlignment(Cell, haCenter);
Worksheet.WriteVertAlignment(Cell, vaCenter);
end;
end;
// Adjust row heights based on content
for Row := 0 to Worksheet.GetLastRowIndex do
Worksheet.WriteRowHeight(Row, NICE_ROWHEIGHT_FACTOR *
Worksheet.CalcAutoRowHeight(Row), Workbook.Units);
// --> !!!! Set page layout: horizontally center the table
Worksheet.PageLayout.Options:=
Worksheet.Pagelayout.Options + [poHorCentered];
// --> !!!! Set page layout: Vertically center the table
Worksheet.PageLayout.Options:=
Worksheet.Pagelayout.Options + [poVertCentered];
// Save the workbook as an XLSX file
Workbook.WriteToFile('WIEZEN.xlsx', sfOOXML, True);
finally
Workbook.Free;
end;
end;