Excel合并单元格
标签(空格分隔): php
phpexcel
# excel导出
public static function downloadExcel($title, $list, $fileName = 'xxx')
{
import("Org.Util.PHPExcel");
import('Org.Util.PHPExcel.IOFactory');
import('Org.Util.PHPExcel.Style.Alignment');
import("Org.Util.PHPExcel.Writer.Excel2007");
$PHPExcel = new PHPExcel;
$PHPSheet = $PHPExcel->getActiveSheet();
# 居中设置
$PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$PHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$start = 2;
# 统计重复的次数
$arrayCountValues = array_count_values(array_column($list, 'number'));
foreach ($list as $k => $v) {
# code...
foreach ($title as $key => $value) {
if ($k == 0) {
$PHPSheet->setCellValue($key.'1', end($value));
}
$i = $k + 2;
$PHPSheet->setCellValue($key.$i, $v[reset($value)]);
# 合并单元格
$PHPSheet->mergeCells('A'.$start.':A'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('B'.$start.':B'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('C'.$start.':C'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('D'.$start.':D'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('E'.$start.':E'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('F'.$start.':F'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('G'.$start.':G'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('H'.$start.':H'.($start+$arrayCountValues[$v['number']]-1));
$PHPSheet->mergeCells('I'.$start.':I'.($start+$arrayCountValues[$v['number']]-1));
}
$start++;
}
$fileName = iconv("UTF-8", "GBK", $fileName.'.xlsx');
$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
header("Pragma: public");
header("Expires: 0");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: max-age=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='.$fileName);
header("Content-Transfer-Encoding:binary");
$PHPWriter->save("php://output");exit;
}
# csv导出
public static function downloadCsv($data = [], $header = [], $fileName= 'xxx') {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
header('Cache-Control: max-age=0');
$fp = fopen('php://output', 'a');
foreach ($header as $key => $value) {
$header[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $header);
$num = 0;
$limit = 100000;
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$num++;
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $row);
}
}