如何在PHPExcel

时间:2016-10-17 06:27:02

标签: sql excel phpexcel

我正在尝试创建excel生成的文件。我想从数据库中获取用户名,然后根据字母表中的每个字母打印名称。我能够按字母顺序创建工作表,但不能在每张工作表上打印名称。 以下是我到目前为止的情况:

<?php
    require_once ('PHPExcel/Classes/PHPExcel.php');
    include('inc/database_connection.php');
    $conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME); 

    $conn->set_charset('utf8_unicode_ci');//if not by default
    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $F = $objPHPExcel->getActiveSheet();

    $Letter='B';
    $Number=2;  

    for($i=321; $i<347; $i++)
    {
        $F = $objPHPExcel->createSheet($i); //Setting index when creating

        $F->setCellValue('A1', "Username")
          ->setCellValue('B1', "Project")   
          ->setCellValue('C1', "Processes");

        $request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
        $result= $conn->query($request);//get the result (ressource)          

        if ($result->num_rows > 0) 
        {
            // output data of each row
            while($row = $result->fetch_assoc()) 
            {      
                $username=$row["username"];
                $F->setCellValue('A'.$Number, ' '.$username.' ');
                $F->getRowDimension('1')->setRowHeight(20);
                $F->getColumnDimension($Letter)->setWidth(30);
                ++$Number;
            }
        } else 
        {
            echo "0 results";
        }                                       

        $F->setTitle(chr($i));      
    }   

// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="HeadCount.xls"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;   
?>

是否可以为每个spreedsheet打印用户名?谢谢。

1 个答案:

答案 0 :(得分:0)

通过删除if statement

解决了问题
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();

for($i=321; $i<347; $i++)
{
    $Letter='B';
    $Number=2;  
    $F = $objPHPExcel->createSheet($i); //Setting index when creating
    $objPHPExcel->setActiveSheetIndex(1);
    $F->setCellValue('A1', "Username")
      ->setCellValue('B1', "Project")   
      ->setCellValue('C1', "Processes");

    $request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
    $result= $conn->query($request);//get the result (ressource)          

        // output data of each row
        while($row = $result->fetch_assoc()) 
        {      
            $username=$row["username"];
            $F->setCellValue('A'.$Number, ' '.$username.' ');
            $F->getRowDimension('1')->setRowHeight(20);
            $F->getColumnDimension($Letter)->setWidth(30);
            ++$Number;
        }                               
    $F->setTitle(chr($i));      
}