Kotchasan Framework Documentation

Kotchasan Framework Documentation

Xls

EN 05 Feb 2026 07:56

Xls

\Kotchasan\Xls is a utility class for exporting data to Microsoft Excel format (.xls) using HTML Table structure.

Usage

Kotchasan\Xls operates as a static class, primarily using the send() method to export data.

use Kotchasan\Xls;

// Table Headers
$header = ['Name', 'Email', 'Phone'];

// Data Rows
$datas = [
    ['John Doe', 'john@example.com', '1234567890'],
    ['Jane Doe', 'jane@example.com', '0987654321']
];

// Export as 'users.xls'
Xls::send('users', $header, $datas);

Methods

send()

Generates the Excel file, sends appropriate headers, and outputs the content for immediate download.

Xls::send('filename', ['Header A', 'Header B'], [['Data A', 'Data B']]);

Parameters:

  • $file (string): Filename without extension (.xls will be appended automatically).
  • $header (array): Array of header strings, or an array with 'rows' key for multi-line headers.
  • $datas (array): Array of data rows (Array of arrays).

Returns:

  • bool: Always returns true.

Multi-line Headers

For complex headers spanning multiple rows, use the rows key:

$header = [
    'rows' => [
        ['Date', 'Description', 'Income', 'Expense', 'Balance'],
        ['', '', 'THB', 'THB', 'THB']
    ]
];
Xls::send('financial_report', $header, $data);

Cell Formatting

Data items (in $datas or $header) can be simple strings or arrays to specify HTML attributes:

$data = [
    [
        'align' => 'center', // HTML attribute (e.g., align="center")
        'value' => 'Centered Text'   // Cell content
    ],
    'Normal Text'
];

Examples

Exporting Database Results

use Kotchasan\Xls;

// Mock data from database
$users = [
    ['id' => 1, 'name' => 'Admin', 'status' => 'Active'],
    ['id' => 2, 'name' => 'User', 'status' => 'Pending']
];

$header = ['ID', 'Name', 'Status'];
$data = [];

foreach ($users as $user) {
    $data[] = [
        $user['id'],
        $user['name'],
        [
            'value' => $user['status'],
            'style' => $user['status'] == 'Active' ? 'color:green' : 'color:red'
        ]
    ];
}

Xls::send('member_list', $header, $data);

Notes

  1. The generated file is technically an HTML Table saved with a .xls extension. Microsoft Excel can open this format, but it is not a native binary Excel file.
  2. send() handles setting HTTP headers (Content-Type, Content-Disposition) and outputs content directly. Ensure no other output is sent before calling this method.
  • Csv - For CSV export