phpexcel cell getstyle applyfromarray

时间:2014-09-09 21:53:57

标签: php phpexcel

我正在尝试更改单元格的颜色和字体粗细,它正在更改所有单元格上的字体。 我做错了吗?

这是我的代码:

<?php

include_once("PHPExcel/PHPExcel.php");

header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');

$workbook = new PHPExcel();

$worksheet = $workbook->getActiveSheet();

$blueBold = array(
    "font" => array(
        "bold" => true,
        "color" => array("rgb" => "0000ff"),
    ),
);
$greenNotBold = array(
    "font" => array(
        "bold" => false,
        "color" => array("rgb" => "00ff00"),
    ),
);

$worksheet->getColumnDimension("A")->setAutoSize(true);

$worksheet->setCellValue("A1", "blue, bold", true)->getStyle()->applyFromArray($blueBold);
$worksheet->setCellValue("A2", "green, not bold", true)->getStyle()->applyFromArray($greenNotBold);


$excelWriter = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
$excelWriter->save("php://output");

发生了什么: 单元格A1和A2始终格式化,最后应用了样式。按顺序添加单元格时

$worksheet->setCellValue("A1", "blue, bold", true)->getStyle()->applyFromArray($blueBold);
$worksheet->setCellValue("A2", "green, not bold", true)->getStyle()->applyFromArray($greenNotBold);
然后它们是绿色而不是粗体。按此顺序添加时

$worksheet->setCellValue("A2", "green, not bold", true)->getStyle()->applyFromArray($greenNotBold);
$worksheet->setCellValue("A1", "blue, bold", true)->getStyle()->applyFromArray($blueBold);

他们是蓝色和粗体

会发生什么:

单元格A1应为蓝色和粗体。单元格A2应为绿色而不是粗体。

1 个答案:

答案 0 :(得分:2)

你在某处清楚地发现了一个错误。

同时(直到我能确定原因并应用修复),我建议

$worksheet->setCellValue("A1", "blue, bold")
    ->getStyle('A1')->applyFromArray($blueBold);
$worksheet->setCellValue("A2", "green, not bold")
    ->getStyle('A2')->applyFromArray($greenNotBold);

代替

修改

此问题的修复程序现已应用于github上的develop分支