Kotchasan Framework Documentation

Kotchasan Framework Documentation

Xls

TH 05 Feb 2026 07:56

Xls

\Kotchasan\Xls สำหรับส่งออกข้อมูลเป็นไฟล์ Excel (.xls) แบบง่าย โดยใช้ HTML Table Format

การใช้งาน

Kotchasan\Xls ทำงานเป็น Static class โดยมีเมธอดหลักคือ send() สำหรับส่งข้อมูลออกเป็นไฟล์ Excel

use Kotchasan\Xls;

// หัวตาราง
$header = ['ชื่อ', 'อีเมล', 'เบอร์โทร'];

// ข้อมูล
$datas = [
    ['สมชาย', 'somchai@example.com', '0812345678'],
    ['สมหญิง', 'somying@example.com', '0898765432']
];

// ส่งออกเป็นไฟล์ 'users.xls'
Xls::send('users', $header, $datas);

Methods

send()

ส่งออกไฟล์ Excel และบังคับให้ดาวน์โหลดทันที

Xls::send('export_filename', ['Col 1', 'Col 2'], [['Data 1', 'Data 2']]);

Parameters:

  • $file (string): ชื่อไฟล์ (ไม่ต้องใส่นามสกุล .xls)
  • $header (array): Array ของหัวตาราง (array of strings) หรือ Array ที่มี key 'rows' สำหรับ header หลายบรรทัด
  • $datas (array): Array ของข้อมูล (Array of arrays)

Returns:

  • bool: true เสมอเมื่อทำงานสำเร็จ

หากต้องการ Header หลายบรรทัด สามารถใช้ key 'rows' ได้:

$header = [
    'rows' => [
        ['วันที่', 'รายละเอียด', 'รับ', 'จ่าย', 'คงเหลือ'],
        ['', '', 'บาท', 'บาท', 'บาท']
    ]
];
Xls::send('report', $header, $data);

การจัดรูปแบบ Cell

ข้อมูลใน $datas หรือ $header สามารถเป็น string ธรรมดา หรือ array เพื่อกำหนด attribute ให้กับ cell ได้:

$data = [
    [
        'align' => 'center', // กำหนด attributes (เช่น align="center")
        'value' => 'ข้อมูล'   // ค่าใน cell
    ],
    'ข้อมูลปกติ'
];

ตัวอย่างการใช้งาน

Export ข้อมูลสมาชิก

use Kotchasan\Xls;

// สมมติข้อมูลจากฐานข้อมูล
$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);

ข้อควรระวัง

  1. ไฟล์ที่ได้จะเป็น HTML Table ที่ save เป็นนามสกุล .xls (ซึ่ง Excel เปิดได้) ไม่ใช่ Binary Excel format แท้ๆ
  2. send() จะทำการส่ง Headers (Content-Type, Content-Disposition) และ echo ข้อมูลทันที ดังนั้นไม่ควรมี output อื่นก่อนหน้านี้

คลาสที่เกี่ยวข้อง

  • Csv - สำหรับ export เป็น CSV