PHPExcel 贴入生成的二维码.php public static function exportCards() { set_time_limit(300); // 设置最大执行时间 $output=[]; // 设置存放数据的空数组 $data = AppExtendCard::where(['is_print'=0])-select(); // 查询数据
public static function exportCards() {
set_time_limit(300); // 设置最大执行时间
$output=[]; // 设置存放数据的空数组
$data = AppExtendCard::where(['is_print'=>0])->select(); // 查询数据
if(empty($data)) return FALSE;
$titles = [ // 设置导出数据的表头
'code' =>'礼品卡号',
'amount'=>'金额',
'expire_time'=>'到期时间',
'card_qr' =>'二维码'
];
array_push($output,$titles); // 压入到空数组中
if($data instanceof Collection) {
$data = $data->toArray(); // 把查询的结果转换成数组 注意 TP5 框架BUG
}
$tmp=[]; // 准备一个空数组 用来存放每一行数据
foreach($data as $item) { // 遍历查询出的数据
foreach ($titles as $key=>$val) {
if(isset($item[$key])){
$tmp['casts'][$key]=$item[$key]; // 拿到表头中指定的字段的数据
}else{
$tmp['casts'][$key] = $item['code']; // 如果是二维码字段就放入想要生成二维码的内容
}
}
array_push($output,$tmp['casts']); // 压入到存放数据的数组中
}
$objPHPExcel = new PHPExcel(); // 实例化表格类
$qrCode = new QrCode(); // 实例化二维码类
$objSheet = $objPHPExcel->getActiveSheet(); // 返回当前活动的对象
$objSheet->getDefaultRowDimension()->setRowHeight(50);
list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString('A1'); //获取操作开始的坐标
$objSheet->setTitle('礼品卡'); // 设置表头
//遍历并写入数据 拿到对应的关系
foreach ($output as $value) {
$currentColumn = $startColumn;
foreach ($value as $key=>$val) {
if($key=='card_qr') { // 判断是不是写二维码
if($startRow<=1) { // 第一行写表头
$objSheet->getCell($currentColumn . $startRow)->setValue($val);
}else{
$objDrawing = new \PHPExcel_Worksheet_MemoryDrawing(); // 实例化一个 PHPExcel 中的类
$objDrawing->setWidth(50); // 设置宽和高
$objDrawing->setHeight(50);
$qrCode->setText($val)->setSize(50)->setPadding(10)->setErrorCorrection('high')->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setImageType(QrCode::IMAGE_TYPE_PNG); // 生成一个二维码
ob_start(); // 开启缓存 用于读取二维码
$qrCode->render(); // 读取二维码
$a = ob_get_contents(); // 拿到缓存中的二维码信息
ob_clean(); // 清楚缓存
$objDrawing->setCoordinates($currentColumn . $startRow);// 设置二维码开始画入得位置
$objDrawing->setImageResource(imagecreatefromstring($a));// 写入excel 注意:Excel 中只能写入本地图片或者是GD生成的图片
$objDrawing->setWorksheet($objSheet); // 写入活动的表格中
}
}else{
$objSheet->getCell($currentColumn . $startRow)->setValue($val); // 写入不是二维码的其他数据
}
++$currentColumn;
}
++$startRow;
}
$objWrite = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); // 按指定格式创建表格
$outputFileName = '礼品卡.xls'; // 表格的名字
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$outputFileName.'"');
header('Cache-Control: max-age=0');
$objWrite->save( 'php://output');
return TRUE;
}
