php 以零开头的字符串/数字的正确格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3054312/
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 08:33:27  来源:igfitidea点击:

Correct format for strings / numbers beginning with zero?

phpphpexcel

提问by Dan

I'm trying to use PHP to create a file containing a list of phone numbers. It's working OK however if the phone number begins with zero, the digit is dropped from the Excel file.

我正在尝试使用 PHP 创建一个包含电话号码列表的文件。它工作正常,但是如果电话号码以零开头,则该数字将从 Excel 文件中删除。

Does anyone know how to set the formatting correctly so that it remains in place?

有谁知道如何正确设置格式以使其保持原位?

回答by Mark Baker

Either:

任何一个:

// Set the value explicitly as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '0029', PHPExcel_Cell_DataType::TYPE_STRING);

or

或者

// Set the value as a number formatted with leading zeroes
$objPHPExcel->getActiveSheet()->setCellValue('A3', 29);
$objPHPExcel->getActiveSheet()->getStyle('A3')->getNumberFormat()->setFormatCode('0000');

回答by Sjoerd

Set the type to string explicitly:

将类型显式设置为字符串:

$type = PHPExcel_Cell_DataType::TYPE_STRING;
$sheet->getCellByColumnAndRow($column, $rowno)->setValueExplicit($value, $type);

回答by Tomasz

This is an old question but I was recently struggling with this issue and I thought it may help someone in the future if I post some additional info here:

这是一个老问题,但我最近在这个问题上苦苦挣扎,我认为如果我在这里发布一些额外的信息,它可能会对将来的某人有所帮助:

Whilst the above answers are correct, the formatting gets lost when you remove a column or row that is located before the formatted cell.

虽然上述答案是正确的,但当您删除位于格式化单元格之前的列或行时,格式会丢失。

The solution that seems to be resistand to that is:

似乎对此有抵抗力的解决方案是:

$cellRichText = new \PHPExcel_RichText($worksheet->getCell($cell));                        
$cellRichText->createText($cellValue);

回答by keepthepeach

If for some reason the answers above don't work, you can simply try to wrap your data in quotes, something like this:

如果由于某种原因上述答案不起作用,您可以简单地尝试将数据用引号括起来,如下所示:

setCellValue('A1, '"' . $phone . '" ')

But your value will be surrounded by quotes in your file as well.

但是您的值也会被文件中的引号包围。

回答by Nishad Aliyar

Use \twith the value like "$phone\t"

\t与值一起使用"$phone\t"

回答by Himal Majumder

In My case, I'm using

就我而言,我正在使用

->setCellValue('A3', ' '0000123456789000' ');

And it's work perfectly.

它的工作完美。