ThinkPHP6ÖÐÔõÑùʵÏÖÊý¾Ýµ¼³ö²Ù×÷£¿
ÔÚwebÓ¦ÓóÌÐòÖУ¬Êý¾Ýµ¼³öÊǷǾ³£¼ûµÄ¹¦Ð§Ö®Ò»¡£ÔÚthinkphp6ÖУ¬Í¨¹ýʹÓõÚÈý·½¿âphpexcel£¬ÎÒÃÇ¿ÉÒÔÇáËɵØʵÏÖÊý¾Ýµ¼³ö¹¦Ð§¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚthinkphp6ÖÐʹÓÃphpexcelʵÏÖÊý¾Ýµ¼³ö²Ù×÷¡£
Ò»¡¢×°ÖÃPHPExcel¿â
Ê×ÏÈ£¬ÎÒÃÇÐèҪװÖÃPHPExcel¿â¡£¿ÉÒÔͨ¹ýComposerÀ´×°Öøÿ⣬Ïêϸ²Ù×÷ÈçÏÂ:
ÔÚÄãµÄÏîĿĿ¼ÏÂÔËÐÐÒÔÏÂÏÂÁ
composer require phpoffice/phpexcel
µÇ¼ºó¸´ÖÆ
×°ÖÃÍê³Éºó£¬¾Í¿ÉÒÔͨ¹ýÒÔÏ´úÂëÀ´¼ÓÔØPHPExcel¿â£º
use PhpOfficePhpSpreadsheetSpreadsheet; use PhpOfficePhpSpreadsheetWriterXlsx;
µÇ¼ºó¸´ÖÆ
¶þ¡¢½¨Éèµ¼³öÒªÁì
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª½¨Éèµ¼³öÒªÁì¡£ÔÚ¸ÃÒªÁìÖУ¬ÎÒÃÇÐèÒª´ÓÊý¾Ý¿âÖлñÈ¡Êý¾Ý£¬²¢½«ÆäдÈëExcelÎļþÖС£ÒÔÏÂÊÇÒ»¸ö»ù±¾Ê¾Àý£º
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
use PhpOfficePhpSpreadsheetSpreadsheet; use PhpOfficePhpSpreadsheetWriterXlsx; public function exportExcel(){ // »ñÈ¡Êý¾Ý $data = Db::table('table_name')->select(); // ½¨ÉèÒ»·ÝеÄExcelÎļþ $spreadsheet = new Spreadsheet(); // ÉèÖÃÊÂÇé±íÃû $spreadsheet->getActiveSheet()->setTitle('Êý¾Ý±í¸ñ'); // ½«Êý¾ÝдÈëÊÂÇé±íÖÐ $spreadsheet->getActiveSheet() ->fromArray($data, null, 'A1'); // ÉúÑÄExcelÎļþ $writer = new Xlsx($spreadsheet); $fileName = 'Êý¾Ý±í¸ñ.xlsx'; header('Content-Disposition: attachment; filename="' . $fileName . '"'); $writer->save('php://output'); }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈͨ¹ýDbÀà´ÓÊý¾Ý¿âÖлñÈ¡Êý¾Ý¡£È»ºó£¬ÎÒÃǽ¨ÉèÁËÒ»¸öеÄSpreadsheet¹¤¾ß£¬²¢½«ÊÂÇé±íÃûÉèÖÃΪ¡°Êý¾Ý±í¸ñ¡±¡£×îºó£¬ÎÒÃÇͨ¹ýfromArray()ÒªÁ콫Êý¾ÝдÈëÊÂÇé±íÖв¢½«ExcelÎļþÉúÑÄÏÂÀ´¡£½«ExcelÎļþÊä³öµ½ä¯ÀÀÆ÷µÄÀú³Ìͨ¹ýheader()º¯ÊýʵÏÖ¡£
Èý¡¢Ìí¼Óµ¼³ö°´Å¥
×îºó£¬ÔÚÐèҪʵÏÖµ¼³ö¹¦Ð§µÄÍøÒ³ÖУ¬ÎÒÃÇÐèÒªÌí¼Óµ¼³ö°´Å¥£¬ÒÔ±ãÓû§¿ÉÒÔÔÚµ¥»÷°´Å¥Ê±´¥·¢µ¼³ö²Ù×÷¡£ÒÔÏÂÊÇʾÀý´úÂ룺
<button type="button" onclick="location.href='<?php echo url("Controller/exportExcel"); ?>'">µ¼³öExcel</button>
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃurl()º¯ÊýÀ´»ñÈ¡µ¼³öÒªÁìµÄURLµØµã£¬²¢½«ÆäÉèÖÃΪ°´Å¥µÄµ¥»÷ÊÂÎñ¡£µ±Óû§µ¥»÷°´Å¥Ê±£¬µ¼³öÒªÁ콫±»Å²Ó㬲¢½«ExcelÎļþÊä³öµ½ä¯ÀÀÆ÷ÖС£
½áÂÛ
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÒѾÏÈÈÝÁËÔõÑùÔÚThinkPHP6ÖÐʹÓÃPHPExcel¿âÀ´ÊµÏÖÊý¾Ýµ¼³ö¹¦Ð§¡£Í¨¹ýʹÓÃÕâ¸öÊÖÒÕ£¬ÎÒÃÇ¿ÉÒÔÇáËɵؽ«Êý¾Ý¿âÖеÄÊý¾Ýµ¼³öµ½ExcelÎļþÖУ¬²¢ÎªÓû§Ìṩ±ãµ±µÄÊý¾Ý½»»¥·½·¨¡£
ÒÔÉϾÍÊÇThinkPHP6ÖÐÔõÑùʵÏÖÊý¾Ýµ¼³ö²Ù×÷£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡