<?php
// 导入PHPExcel库
require_once 'PHPExcel.php';
include("conn.php");
// 创建一个新的PHPExcel对象
$objPHPExcel = new PHPExcel();
// 设置活动工作表
$objPHPExcel->setActiveSheetIndex(0);
// 从MySQL数据库中获取数据
$sql = "SELECT id,xm1,xm2 FROM t1 limit 10";
$result = mysql_query($sql);
// 设置表头
$columns = array('列1', '列2', '列3');
$columnIndex = 0;
$rowIndex = 1;
foreach($columns as $columnName) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($columnIndex, $rowIndex, $columnName);
$columnIndex++;
}
// 填充数据
$rowIndex = 2;
while($row = mysql_fetch_assoc($result)) {
$columnIndex = 0;
foreach($row as $cellValue) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($columnIndex, $rowIndex, $cellValue);
$columnIndex++;
}
$rowIndex++;
}
// 设置文件名和格式
$filename = 'filename.xlsx';
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
// 输出Excel文件到浏览器
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
?>
PHPExcel导出简单实例
最新推荐文章于 2024-04-28 11:25:26 发布