【问题标题】:PHPExcel generatting some random characters?PHPExcel生成一些随机字符?
【发布时间】: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 文件

标签: php phpexcel


【解决方案1】:

看来,您的 SQL 语法有错误:

//use double quotes here, not single - otherwise $id won't be substituted
$SQL = "SELECT * from stud_master where stud_id=$id";
$rs=mysqli_query($Link, $SQL);//get the result (ressource)

但最好使用准备好的语句来防止 SQL 注入。

【讨论】:

  • thnk 4035 我指出了错误你能告诉我更多什么时候使用单引号,什么时候双引号我通常看到很多人使用单引号
  • @Optimmus 这里是最基本的区别:stackoverflow.com/a/3446245/789186
猜你喜欢
  • 2012-05-10
  • 1970-01-01
  • 2012-11-21
  • 2010-10-18
  • 2011-09-26
  • 1970-01-01
  • 2017-08-01
相关资源
最近更新 更多