我想使用php在excel表(xlx)中编写数组

时间:2016-02-18 09:57:54

标签: php arrays excel

我想在Excel表格中写一个数组:有人能帮帮我吗?如何在Excel工作表中编写此数组?

我的阵列:

Array
(
[1] => Array
    (
        [1] => age
        [2] => name
        [3] => gender
    )

[2] => Array
    (
        [1] => 12
        [2] => alexander
        [3] => male

    )

[3] => Array
    (
        [1] => 18
        [2] => shine
        [3] => female
    )

)

我想要这个输出:

enter image description here

我想在Excel工作表中编写此数组,并在编写数组后,将文件下载为Excel电子表格(xlsx)。

3 个答案:

答案 0 :(得分:1)

您好,您可以将数组存储为csv文件或使用Excel php库之一创建excel文件,您可以检查此库: PHPExcel

答案 1 :(得分:0)

我已经在我的开发服务器上测试了这段代码,它应该可以完美运行:

  1. 获取PHPExcel library并将其放在您的服务器上。
  2. 使用此代码:

    // Include the PHPExcel libraries
    require_once "PHPExcel/PHPExcel.php"; // Or whatver the path to your PHPExcel library is
    require_once "PHPExcel/PHPExcel/IOFactory.php";
    
    // Set up your input data array
    $data = array(
        array("age", "name", "gender"),
        array("12", "alexander", "male"),
        array("18", "shine", "female"),
    );
    
    // Create the PHPExcel object
    $xl = new PHPExcel();
    
    // Write the data into the new spreadsheet starting at cell A1
    $xl->getActiveSheet()->fromArray($data, NULL, 'A1');
    
    // Create a spreadsheet writer, in this case for Excel 2007 (xlsx)
    $objWriter = PHPExcel_IOFactory::createWriter($xl, 'Excel2007');
    
    // Set the appropriate headers for the download:
    header("Content-type: application/octet-stream");
    
    // Name the file
    header("Content-Disposition: attachment; filename=Export.xlsx");
    $objWriter->save('php://output');
    // We're finished!
    die; 
    
  3. 或者,如果您想对刚刚生成的文件执行不同的操作,可以使用以下内容替换$objWriter之后的所有内容:

    ob_start();
    $objWriter->save('php://output');
    $fileContents = ob_get_clean();
    

答案 2 :(得分:0)

我了解您要生成.XLS文件。对? 以下代码可以。

require_once "PHPExcel/PHPExcel.php"; //the path to your PHPExcel library 
require_once "PHPExcel/PHPExcel/IOFactory.php";

    // Set up your input data array
    $data = array(
        array("age", "name", "gender"),
        array("12", "alexander", "male"),
        array("18", "shine", "female"),
    );
$name ="sheet name";
$objPHPExcel = new PHPExcel();
$objWriter  = array();
$objWorkSheet = $objPHPExcel->createSheet();            
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle($name);
$objPHPExcel->getActiveSheet()->fromArray($data);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\""filename.xls");
header('Cache-Control: max-age=0');
ob_get_clean();
$objWriter->save('php://output');
ob_end_flush();
exit;