首先我们看下导出的HTML
接着我们看下Index/excelExport 导出的PHP代码:
$list = M("user")->field("id,username,password")->order("id DESC")->limit(50)->select();
$title = array('ID', '用户名', '密码'); //设置要导出excel的表头
exportExcel($list, '素材火', $title);
exportExcel方法如下:
function exportExcel($data, $savefile = null, $title = null, $sheetname = 'sheet1') {
import("Org.Util.PHPExcel");
//若没有指定文件名则为当前时间戳
if (is_null($savefile)) {
$savefile = time();
}
//若指字了excel表头,则把表单追加到正文内容前面去
if (is_array($title)) {
array_unshift($data, $title);
}
$objPHPExcel = new PHPExcel();
//Excel内容
$head_num = count($data);
foreach ($data as $k => $v) {
$obj = $objPHPExcel->setActiveSheetIndex(0);
$row = $k + 1; //行
$nn = 0;
foreach ($v as $vv) {
$col = chr(65 + $nn); //列
$obj->setCellValue($col . $row, $vv); //列,行,值
$nn++;
}
}
//设置列头标题
for ($i = 0; $i < $head_num - 1; $i++) {
$alpha = chr(65 + $i);
$objPHPExcel->getActiveSheet()->getColumnDimension($alpha)->setAutoSize(true); //单元宽度自适应
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setName("Candara"); //设置字体
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setSize(12); //设置大小
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLACK); //设置颜色
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //水平居中
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
$objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setBold(true); //加粗
}
$objPHPExcel->getActiveSheet()->setTitle($sheetname); //题目
$objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $savefile . '.xls"'); //文件名称
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); //Excel5 Excel2007
$objWriter->save('php://output');
}
接着我们看下导入的表单:
注意:phpexcel是一个免费的开源包了,我们只要下载之后在包中有很多的例子告诉我们如何来使用它,打开参考来修改即可。