php知识总结程序员IT@程序员猿媛

PhpSpreadsheet导出Csv

2019-04-13  本文已影响16人  响呼雷
 /**
     * @param $data 数据 
     * @param $title 头部
     * @param string $name 文件名
     * @throws PhpSpreadsheet\Exception
     * @throws Writer\Exception
     * 导出表格
     */
$data =  [{"title":"苹果","hostorySale":"21","todaySale":"38","number":"22","price":"100.00","sale_create_time":"1554345468","sale_create_time":"1554345468"}];
$data = json_decode($data,true);
$title  =   ['商品名', '原库存', '历史销量', '今日销量', '规格数量', '金额', '开始统计日期'];
public function export($data,$title,$name = 'LiveSale')
    {
        $spreadsheet = new PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
        }
        $row = 2;
        foreach ($data as $item) {
            $column = 1;
            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value."\t");
                $column++;
            }
            $row++;
        }
        $writer = PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'Csv');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$name.'.csv');
        header('Cache-Control: max-age=0');
        $writer->setUseBOM(true);
        $writer->save('php://output');
        exit;
    }
上一篇下一篇

猜你喜欢

热点阅读