phpexcel 和 csv 使用 CI zip 库保存到 zip

phpexcel and csv save to zip using CI zip library

我想导出一些 xlsx 和 csv 格式的数据。最近我创建了一些功能来做到这一点。我的想法是: 1.save 临时文件中的 xlsx 和 csv, 2.将其添加到zip库 3.下载它。

我尝试了一些功能,csv 在 zip 中显示了输出,但是 excel 没有显示任何输出。没有错误,但是 excel 文件没有保存在 zip 文件中

这是我创建 excel 文件的函数

public function createExcel($id){
        $excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
        $excel->setActiveSheetIndex(0);

        $resultExcel = $this->AdminM->getDataExcel($id);
        $rows = 3;

        foreach ($resultExcel->result() as $rowExcel){
            $excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
            $rows++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx',$objWriter->save('assets/Haha.xlsx'));

    }

这里是创建 csv 文件的函数,

public function createCSV($id){
        $csv = fopen("php://temp", "rw");

        fputcsv($csv, array('Name', 'Email', 'Birthdate'));

        $dataCSV = $this->AdminM->getDataCSV($id);
        foreach ($dataCSV as $row){
            fputcsv($csv, $row);
        }

        global $fileCSV;
        $fileCSV = stream_get_contents($csv,-1,0);

        fclose($csv);

        $this->zip->add_data('csv'.date('').date('Y_M_d_H_i_s').'.csv',$fileCSV);
    }

这里是组装函数的代码,同时下载它。

public function download(){
        $id = $this->input->post('id');
        $this->createCSV($id);
        $this->createExcel($id);
        $this->zip->download('testing.zip');
    }

我希望同时下载 csv 和 excel

尝试先保存 xls 文件,然后使用 PHPExcel_IOFactory::load 加载它,然后将加载的 xls 文件作为 zip 参数传递:

public function createExcel($id){
    $excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
    $excel->setActiveSheetIndex(0);

    $resultExcel = $this->AdminM->getDataExcel($id);
    $rows = 3;

    foreach ($resultExcel->result() as $rowExcel){
        $excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
        $excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
        $rows++;
    }

    $xls_name = 'assets/Haha.xlsx';
    $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
    $objWriter->save($xls_name);
    $objPHPExcel = PHPExcel_IOFactory::load($xls_name);
    $this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx', $objPHPExcel);
}