关于Excel读取写入导出

1,常见问题

由于PHPExcel没有命名空间,因此导入是个问题,解决方案之一如下:

将PHPExcel放在vendor下边,在Class类名引入头部

require_once '../vendor/phpoffice/phpexcel/Classes/PHPExcel.php';

2,读取Excel的内容

public function readPriceXsl($xsl_path)
{
        $inputFileName = substr($xsl_path,1);           // 移除路径的/
        // $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);          // 此处是phpspreadsheet的使用方法
        // $objReader = \PHPExcel_IOFactory::createReader($inputFileType);          // 此处是phpspreadsheet的使用方法
        $inputFileType = IOFactory::identify($inputFileName);
        $objReader = IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);

        $h1 = $objPHPExcel->getSheet(0)->getCell('H1')->getFormattedValue();
        $data = [
            'h1' => $h1,  //版本
        ];
        return $data;
}

说明:
getSheet(0) 读取第一个sheet表格

getActiveSheet() 读取第当前活跃的sheet表格

getValue() 获取单元格的Text文本(公式本身)

getFormattedValue() 获取单元格的的值(公式计算后的值)

3,将内容写入Excel

public function savePath1TOPath3($path1,$ver_id)
{
        // 读取
        $data = $this->readNewPriceXsl($path1);

        $path = 'uploads/sample.xls';  // 读取模板,替换值
        $inputFileName = $path;
        
        // 此处使用的是phpspreadsheet
        $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
        $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        
        $objPHPExcel->getActiveSheet()->setCellValue('A2',$data['a2']);
        
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $path3 = 'uploads/price_excel/' . time() . '.xls';
        $result = $objWriter->save($path3);         // 保存新的文件
        // 将路径保存到数据库
        $verModel = new VersionModel();
        $result = $verModel->save(['path3' => '/'.$path3],['id' => $ver_id]);
        if ($result === false){
            throw new Exception($verModel->getError());
        }
        return $data;
}

说明:
setCellValue 设置单元格的值

$objWriter->save() 保存excel,如果带上参数,即保存新文件,否则原文件

3,Excel的导出

public function export()
{
        //创建对象
        $excel = new \PHPExcel();

        $data = array();
        foreach ($infos as $key=>$val) {
            if ($infos[$key]['path3']){  // 有的话获取数据,循环遍历每个报价表的数据
             
                $data[] = $this->readPriceExcel($infos[$key]['path3']);
                $a3 = Cache::get('pro_name_'.$infos[$key]['path3']);
            }
        }
        $a3 = Cache::get('pro_name_');

        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        
        // 进行一系列操作
        
        // 激活当前表
        $excel->setActiveSheetIndex();
        ob_end_clean();//清除缓冲区,避免乱码

        // 创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename=' . (strtr('总报价表', array(' ' => '_')) . '_' . time()) . '.xls');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
}

说明:
$write->save('php://output') 将Excel输出到浏览器

4,Excel导出常见样式设置

设置水平居中

$excel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

设置垂直居中

$excel->getActiveSheet()->getStyle('A1:H3')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

设置单元格行高

$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(25);

设置单元格长度

$excel->getActiveSheet()->getColumnDimension('B')->setWidth(18);

设置字体样式

$excel->getActiveSheet()->getStyle('B1')->getFont()->setName('宋体')->setSize(15)->setBold(true);

设置字体颜色
$excel->getActiveSheet()->getStyle('A3')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_RED);

合并单元格
$excel->getActiveSheet()->mergeCells('C1:H1');

设置单元格边框

$styleThinBlackBorderOutline = array(
    'borders' => array(
           'allborders' => array( //设置全部边框
           'style' => \PHPExcel_Style_Border::BORDER_DASHED, //粗的是thick
           'color' => array ('argb' => 'FF000000'),
            ),
     ),
);
$excel->getActiveSheet()->getStyle("$a:$b")->applyFromArray($styleThinBlackBorderOutline);

设置换行

        $content = '三、付款方式:'.chr(10);  // chr(10)为换行
        $content .= '1.定金:合同签订三天内支付合同总额的'.$arr[1].'%;'.chr(10);
        $content .= '2.设备发货前支付合同总额的'.$arr[2].'%;'.chr(10);
        $content .= '3.设备移交使用一个月内支付合同总额的'.$arr[3].'%;'.chr(10);
        $a = 'A'.($row3+1);
        $b = 'H'.($row3+5);
        $excel->getActiveSheet()->setCellValue('A'.($row3+1), $content);    // 设置内容
        $excel->getActiveSheet()->mergeCells("$a:$b");  // 合并单元格
        $excel->getActiveSheet()->getStyle($a)->getAlignment()->setWrapText(true);  // 换行

5,Excel导出带图片

public function look_down()
{
        $data = Db::name('user')->select();

        // 导出Excel
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");      // 带图片的核心插件
        import("Org.Util.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new \PHPExcel();

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objActSheet = $objPHPExcel->getActiveSheet();

        // 标题
        $objActSheet->setCellValue('A1', 'ID');
        $objActSheet->setCellValue('B1', '昵称');
        $objActSheet->setCellValue('C1', '头像');

        // 内容
        foreach($data as $k=>$v){
            $k +=2;
            $objActSheet->setCellValue('A'.$k, $v['id']);
            $objActSheet->setCellValue('B'.$k, $v['nickname']);

            // 图片生成
            $objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
            $image = './uploads/face/'.$v['head_img'];      // 请勿漏掉upload之前的./
            $objDrawing[$k]->setPath($image);
            // 设置宽度高度
            $objDrawing[$k]->setHeight(80);     // 图片高度
            $objDrawing[$k]->setWidth(80);      // 图片宽度
            /*设置图片要插入的单元格*/
            $objDrawing[$k]->setCoordinates('C'.$k);
            // 图片偏移距离
            $objDrawing[$k]->setOffsetX(12);
            $objDrawing[$k]->setOffsetY(12);
            $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());

            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(80);
        }

        $fileName = '用户表';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');        // 文件通过浏览器下载
}

6,注意事项

以下为本人踩过的Excel的坑,请留意

  • PHPExcel为国外插件,至今没有中文文档;
  • PHPExcel已废弃,没有再更新,功能上难免有一些bug,建议使用phpspreadsheet;
  • 无论是PHPExcel还是phpspreadsheet,都无法读取引用的公式(INDIRECT);

你可能感兴趣的:(关于Excel读取写入导出)