………..
uses
Windows,Dialogs, Interfaces, Classes, SysUtils, FileUtil,
Forms, Controls, ExtCtrls, StdCtrls, ComCtrls, Graphics, Menus,
Grids, Buttons, IniFiles,Printers, OSPrinters, PrintersDlgs,
DateUtils, Variants, lMessages, LCLProc, LCLType, LCLIntf,
fpsexport, fpSpreadsheet, fpstypes, fpsUtils, xlsxooxml;
const
HEADER_FONT_SIZE = 11; // in Points
DEFAULT_FONT_SIZE = 15; // 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;
tmpColCountArr: array of Integer; //col length array
…….
……
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);
[color=red]// --> !!!! Set page layout: horizontally center the table[/color]
[b] Worksheet.PageLayout.HorizontalCentered := True;[/b]
// Save the workbook as an XLSX file
Workbook.WriteToFile('WIEZEN.xlsx', sfOOXML, True);
finally
Workbook.Free;
end;