php phpexcel在单元格范围内设置数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4944301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:13  来源:igfitidea点击:

phpexcel set data type on range of cells

phpphpexcel

提问by Ashley

With PHPExcel, I'm using:

使用PHPExcel,我正在使用:

$workSheet->fromArray($array);

$workSheet->fromArray($array);

To set my data. However, one column needs to be set as string (a number with a leading zero, the leading zero gets cut off if not set to string). If I wasn't using the fromArraymethod, I could set the data type using PHPExcel_Worksheet::setCellValueExplicit().

设置我的数据。但是,需要将一列设置为字符串(带有前导零的数字,如果未设置为字符串,前导零将被截断)。如果我没有使用该fromArray方法,我可以使用PHPExcel_Worksheet::setCellValueExplicit().

However, I want to do this using a range of columns. Ideally something like this:

但是,我想使用一系列列来做到这一点。理想情况下是这样的:

$worksheet->getCell('A1:A50')->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);

But looking at the code, getCellwon't allow a range, only a single cell. How can I do this?

但是查看代码,getCell不允许一个范围,只有一个单元格。我怎样才能做到这一点?

采纳答案by Mark Baker

There is currently no method in PHPExcel that will allow you to set the data type for a range of cells, only for an individual cell.

PHPExcel 中目前没有允许您为一系列单元格设置数据类型的方法,只能为单个单元格设置。

There are a couple of options... the harder would be to write a custom Cell Value Binder that automatically sets the data type for those cells to string when the cell value is set by fromArray().

有几个选项......更难的是编写一个自定义的单元格值绑定器,当单元格值由 fromArray() 设置时,它会自动将这些单元格的数据类型设置为字符串。

What you could do instead (and is far easier), is to leave the datatype as a number, and the value as a numeric, but to set a number format mask which tells Excel to display the numbers with leading zeroes.

你可以做的(而且更容易)是将数据类型保留为数字,将值保留为数字,但设置一个数字格式掩码,告诉 Excel 显示带有前导零的数字。

$objPHPExcel->getActiveSheet()->getStyle('L3:N2048')
                              ->getNumberFormat()->setFormatCode('0000');