使用phpExcel类新数据库中数据导出excel表


首先在phpExcel官网下载最新的类文件,下面是一个小例子,对中文乱码进行了处理


/** PHPExcel */
require_once '../Classes/PHPExcel.php';


// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

//连接数据库获取数据
$conn=mysql_connect('localhost','root','');
if(!$conn)die('数据库连接失败');
mysql_select_db('test');
mysql_set_charset('utf8');

$sql = "SELECT * FROM orders";
$query = mysql_query($sql);
$objPHPExcel->setActiveSheetIndex(0)
     ->setCellValue('A1', mb_convert_encoding('序号','utf-8','gbk'))
      ->setCellValue('B1', mb_convert_encoding('真实姓名','utf-8','gbk'))
       ->setCellValue('C1', mb_convert_encoding('金钱','utf-8','gbk'));
$num = 2;
while($row= mysql_fetch_array($query)){
    $objPHPExcel->setActiveSheetIndex(0)
     ->setCellValue('A'.$num, $row['id'])
      ->setCellValue('B'.$num, $row['realname'])
       ->setCellValue('C'.$num, $row['momeny']);
    
    $num++;
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;




你可能感兴趣的:(phpexcel)