Kotchasan Framework Documentation
Xls
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 returnstrue.
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
- The generated file is technically an HTML Table saved with a
.xlsextension. Microsoft Excel can open this format, but it is not a native binary Excel file. send()handles setting HTTP headers (Content-Type,Content-Disposition) and outputs content directly. Ensure no other output is sent before calling this method.
Related Classes
- Csv - For CSV export