简体   繁体   English

使用PHP Excel读取XLS文件时,如何检测单元格是否为粗体?

[英]When reading an XLS file using PHP Excel, how can I detect if a cell is bold?

I have an Excel 2007 xlsx document with "BC/B22--" in cell L2. 我在单元格L2中有一个带有“ BC / B22--”的Excel 2007 xlsx文档。 It is in bold, and coloured red. 它以粗体显示,并呈红色。 Using PHPExcel (v1.8.0, 2014-03-02) I want to detect whether the cell is bold or not, but I can only get at the value "BC/B22--", and no styling info. 我想使用PHPExcel(v1.8.0,2014-03-02)检测单元格是否为粗体,但是我只能得到“ BC / B22--”值,而没有样式信息。

This is my code: 这是我的代码:

$inputFileType = PHPExcel_IOFactory::identify($sFilepath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);  
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load($sFilepath);
$sheet = $objPHPExcel->setActiveSheetIndex(0); 
$cell = $sheet->getCellByColumnAndRow(11,2);

$v = $cell->getValue();
var_dump($v);
// Echoes: string(8) "BC/B22--" 

$rte = $cell->getValue()->getRichTextElements();
// Error: "Call to a member function getRichTextElements() on a non-object"

echo ($cell->getValue() instanceof PHPExcel_RichText) ? 
    "instance" : "no instance";
// Echoes "no instance"

It all depends on whether the cell contains simple text content and bold is set as a cell style, or if the cell content is a rich text object. 这完全取决于该单元格是否包含简单的文本内容以及将粗体设置为单元格样式还是该单元格内容是富文本对象。

If $cell->getValue() returns a string, then you need to test the style of the cell: 如果$cell->getValue()返回一个字符串,则需要测试单元格的样式:

$isBold = $cell->getStyle()->getFont()->getBold();

Otherwise, if $cell->getValue() returns a Rich Text Object, then you need to walk that Rich Text object searching to see if any part of it is bolded: 否则,如果$cell->getValue()返回RTF对象,则需要遍历该RTF对象以查看其任何部分是否加粗:

$isBold = false;
$elements = $cell->getValue()->getRichTextElements();
foreach ($elements as $element) {
    if ($element instanceof PHPExcel_RichText_Run) {
        $isBold |= $element->getFont()->getBold();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM