【发布时间】:2015-04-17 10:41:46
【问题描述】:
我的任务是分别生成每个学生的 excel 表,所以我使用 PHPExcel lib 来执行任务
<?php
$host='localhost'; $user='root'; $pass=''; $DataBase='college';//define the correct values
// open the connexion to the databases server
$Link=@mysqli_connect($host,$user,$pass,$DataBase) or die('Can\'t connect !');
mysqli_set_charset($Link, 'utf8');//if not by default
//your request
if(isset($_GET['stud_id'])){
$id=$_GET['stud_id'];
$SQL='SELECT * from stud_master where stud_id=$id';
$rs=mysqli_query($Link, $SQL);//get the result (ressource)
/** Include PHPExcel */
require_once 'ec/Classes/PHPExcel.php';//change if necessary
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F=$objPHPExcel->getActiveSheet();
$Line=1;
while($Trs=mysqli_fetch_assoc($rs)){//extract each record
$F->
setCellValue('A'.$Line, $Trs['stud_id'])->
setCellValue('B'.$Line, $Trs['course_id'])->
setCellValue('C'.$Line, $Trs['fname'])->
setCellValue('D'.$Line, $Trs['mname'])->
setCellValue('E'.$Line, $Trs['lname']);//write in the sheet
++$Line;
}
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
【问题讨论】:
-
您的脚本似乎正在为您的 MySQL 访问生成警告,因此请修复该问题
-
为什么当我尝试生成整个表格的 excel 表时会生成这些随机字符,但当我将它用于单个 id 时,它会失败......
-
那些“随机”字符是实际的 Excel 文件字节流......但是因为您在输出中也有那些纯文本警告,它们正在破坏 Excel 文件......修复那些警告....从修复
mysql_fetch_assoc()问题开始,其余的应该自行修复 -
如果
$id没有设置,因为$_GET['stud_id']没有设置,你正试图将一个不存在的变量注入你的SQL,这会产生警告......有一个你需要解决的问题 -
感谢您提出的宝贵建议,即一个警告正在破坏 excel 文件