- 先读取存放在服务器项目中的原始excel表格
//原文件路径
$filePath = public_path() . "checklist.xlsx";
$file = IOFactory::load($filePath);
$sheet = $file->getActiveSheet();
- 向表格中填充数据
$sheet->setCellValueByColumnAndRow(12, 3, date('Y年m月d日',strtotime($date)));
$row = 9; //从第9行开始
foreach ($list as $item) {
//云商通订单号
$sheet->setCellValueByColumnAndRow(1, $row, $item['orderNo']."\t");
//订单类型
$sheet->setCellValueByColumnAndRow(2, $row, $item['tradeType']);
//交易金额
$sheet->setCellValueByColumnAndRow(3, $row, $item['chgAmount']);
//手续费
$sheet->setCellValueByColumnAndRow(4, $row, $item['channelFee']);
//交易时间
$sheet->setCellValueByColumnAndRow(5, $row, $item['changeTime']);
//商户订单编号
$sheet->setCellValueByColumnAndRow(6, $row, $item['bizOrderNo']);
//支付方式
$sheet->setCellValueByColumnAndRow(16, $row, $item['tradeType']);
$row++;
}
- 设置填充内容字体大小和样式
//加粗并使用8号字体
$sheet->getStyle("L3")
->getFont()->setBold(true)->setSize(8);
$sheet->getStyle("A9:W33")
->getFont()->setBold(true)->setSize(8);
- 生成文件url
$exportCache = new ExportCache();
$src = $exportCache->getSrc();
//文件不存在 创建文件
if (!file_exists($src)) {
mkdir($src, 0775, true);
}
//文件名
$fileName = $date.'对账单.xlsx';
// 生成文件路径
$writer->save($src . $fileName);
//设置本地excel返回下载地址
$vars = ['file' => $exportCache->setFile($fileName)];
return (string)url("index/download/export", $vars, false, true);
此处会返回一个链接
访问返回的链接即可下载新的excel表格
如果在结尾加上
$url = (string)url('index/download/export', $vars, false, true);
header("Content-Type:application/octet-stream");
header("Content-Disposition:attachment;filename=".basename($fileName));
readfile($url);
会直接进行下载excel表格,无需在进行二次访问