我有下面的代码但是当我通过导入过程运行我的CSV时,我的前导零消失了。例如,我有一个带有数字的字段,如" 0010"但是在它来自下面的代码后,数字是" 10"。有人有建议吗?
$objPHPExcel = new PHPExcel();
function ci_import($inputFileName){
//echo "calling....";exit;
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
$sheets = count($objPHPExcel->getAllSheets());
//echo $sheets;
//echo "<pre>";
$arr=array();
foreach($objPHPExcel->getAllSheets() as $sheet){
$title = $sheet->getTitle();
$arr[$title]=array();
$rows= array();
// fetch the data
foreach ($sheet->getRowIterator() as $row)
{
$cols= array();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // This loops all cells,
foreach ($cellIterator as $cell)
{
$cols[]=$cell->getValue();
}
$rows[] = $cols;
}
$arr[$title]=$rows;
}
return $arr;
print_r( $arr);
}
&#13;
答案 0 :(得分:1)
数字没有前导零;但PHPExcel的CSV阅读器会识别值0010
是数字并将其转换为数字10
,这是完全正确的,并且(仅供参考)正是MS Excel CSV阅读器所做的。< / p>
如果要将此值视为字符串,或将其格式化为带有前导零的4位数字,则需要创建一个自定义绑定器,将其指定为导入值的规则。
class PHPExcel_Cell_MyValueBinder extends PHPExcel_Cell_DefaultValueBinder
implements PHPExcel_Cell_IValueBinder
{
public function bindValue(PHPExcel_Cell $cell, $value = null)
{
// sanitize UTF-8 strings
if (is_string($value)) {
$value = PHPExcel_Shared_String::SanitizeUTF8($value);
}
// Implement your own override logic
if (is_string($value) && $value[0] == '0') {
// Here, we're just enforcing that the value should be treated
// as a string, but we could convert it to a numeric and apply
// a format mask to the cell instead
$cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
return true;
}
// Not bound yet? Use default value parent...
return parent::bindValue($cell, $value);
}
}
要避免自动装带器出现任何问题,请在/ Classes / PHPExcel / Cell目录中创建。否则,为类提供您自己的非PHPExcel名称,并确保它是独立加载的。
然后,在加载文件之前,请指明应使用自定义活页夹:
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_MyValueBinder() );