PHPExcel-从数组上载时将单元格设置为字符串 [英] PHPExcel - Set cells as string while uploading from Array

查看:424
本文介绍了PHPExcel-从数组上载时将单元格设置为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$objPHPExcel->getActiveSheet()->fromArray($dataArray,null,"A2")

我有上面的代码行.问题是,我不擅长迭代,我希望将所有单元格值都设置为STRING,以避免自动修改以零开头的文本.

I've the above line of code. The problem is, I am not good at iterating and I want all the cell values to be set as STRING so as to avoid automated modifications of texts leading zeros.

P.S.此外,将感谢您将用于设置为选择性列的STRING的代码.

P.S. In Addition, code for setting as STRING for selective columns will be appreciated.

谢谢!

推荐答案

单独设置单元格值时,可以选择显式设置数据类型,但是当使用fromArray()方法时,就没有此设置选项.

When you set cell values individually, you have the option of setting the datatype explicitly, but when you use the fromArray() method, you don't have this option.

但是,默认情况下,PHP使用默认值绑定器从传递的值中识别数据类型,并相应地设置单元格数据类型.此默认行为在类/PHPExcel/Cell/DefaultValueBinder.php中定义.

However, by default, PHP uses a default value binder to identify datatypes from the values passed, and set the cell datatype accordingly. This default behaviour is defined in a class /PHPExcel/Cell/DefaultValueBinder.php.

因此,您可以按照

So you can create your own value binder, as described in the PHPExcel Documentation, that would set every value as a string datatype.

类似的东西:

class PHPExcel_Cell_MyColumnValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
    protected $stringColumns = [];

    public function __construct(array $stringColumnList = []) {
        // Accept a list of columns that will always be set as strings
        $this->stringColumns = $stringColumnList;
    }

    public function bindValue(PHPExcel_Cell $cell, $value = null)
    {
        // If the cell is one of our columns to set as a string...
        if (in_array($cell->getColumn(), $this->stringColumns)) {
            // ... then we cast it to a string and explicitly set it as a string
            $cell->setValueExplicit((string) $value, PHPExcel_Cell_DataType::TYPE_STRING);
            return true;
        }
        // Otherwise, use the default behaviour
        return parent::bindValue($cell, $value);
    }
}

// Instantiate our custom binder, with a list of columns, and tell PHPExcel to use it
PHPExcel_Cell::setValueBinder(new PHPExcel_Cell_MyColumnValueBinder(['A', 'B', 'C', 'E', 'F']));

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->fromArray($dataArray,null,"A2");

这篇关于PHPExcel-从数组上载时将单元格设置为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆