ThinkPHP3.2.3 结合 PHPExcel 导出

/**

*
* 导出Excel   调用
*/
function export(){
$xlsName = "Qrcode";
$xlsCell = array(
  array('qrid','序列'),
  array('theonly','唯一码'),
  array('tag','回复语模板'),
  array('product_name','产品名称'),
  array('click','点击量'),
  array('qrcode_pic','二维码图片'),
  array('add_time','创建时间')
);

//实例化查询数据
$xlsModel = M('qrcode');
$xlsData = $xlsModel
  ->join('mr_reply ON mr_qrcode.replyid = mr_reply.id')
  ->join('mr_product ON mr_qrcode.pid = mr_product.id')
  ->select();
 $this->exportExcel($xlsName,$xlsCell,$xlsData);
}


/* 导出excel函数 */
public function exportExcel($expTitle,$expCellName,$expTableData){
  $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
  $fileName = $_SESSION['account'].date('二维码数据_Ymd');//or $xlsTitle 文件名称可根据自己情况设定
  $cellNum = count($expCellName);
  $dataNum = count($expTableData);

  //实例化
  vendor("PHPExcel.PHPExcel");
  $objPHPExcel = new \PHPExcel();

$cellName = array('A','B','C','D','E','F','G');

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('5');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('20');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('15');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('20');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth('10');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth('30');//设置列宽
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth('20');//设置列宽



$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
//$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.' Export time:'.date('Y-m-d H:i:s'));
for($i=0;$i<$cellNum;$i++){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
}
// Miscellaneous glyphs, UTF-8
for($i=0;$i<$dataNum;$i++){
for($j=0;$j<$cellNum;$j++){
  $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
}
}

header('pragma:public');
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}

首先下载PHPExcel  放入ThinkPHP\Library\Vendor下面 可更改文件名为PHPExcel

PHPExcel下载地址:http://phpexcel.codeplex.com/

转载于:https://www.cnblogs.com/nonoleng/p/5630077.html

你可能感兴趣的:(php)