Phpspreadsheet单元格未按指定格式设置

nxowjjhe  于 2022-12-21  发布在  PHP
关注(0)|答案(1)|浏览(141)

我试图在单元格上设置**“常规”**以外的格式,但它们仍为“常规”格式。
这是我的代码的简化:

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

// Data sample
$data = [
    ['Pete', 1, 'peter@foo.com', 23, 600000000000],
    ['Carl', 2, 'carl@bar.com', 29, 600000000000],
];
// Format for each column
$column_types = [
            'Name'                  => DataType::TYPE_STRING,
            'Id'                    => DataType::TYPE_NUMERIC,
            'Email'                 => DataType::TYPE_STRING, 
            'Age'                   => DataType::TYPE_NUMERIC,
            'Commerce ID'           => DataType::TYPE_NUMERIC,
];
$column_types = array_values($data);

$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$sheet = $spreadsheet->getActiveSheet();

foreach ($data as $row => $row_data) {
    $i = 1;
    $row++;
    foreach ($row_data as $value) {
        // VALUE IS SET, BUT NOT DATA TYPE!!
        $sheet->getCellByColumnAndRow($i, $row)->setValueExplicit($value, $column_types[$i - 1]);
        $i++;
    }
}

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save(PATH_TEMP . 'my_excel.xlsx');

现在,当我打开结果xlsx时,所有的单元格都将是“General”,而不是Number,以防它被赋值为DataType::TYPE_NUMERIC。更糟糕的是,最后一列,即**“60000000000”,被转换为“6E+11”**,尽管它仍然是一个“General”单元格。
你知道我该怎么做吗?

aiazj4mn

aiazj4mn1#

必须按如下方式设置单元样式的数字格式(简化示例):

$sheet->getCellByColumnAndRow(1, 1)
    ->setValueExplicit(6000000000000, DataType::TYPE_NUMERIC)
    ->getStyle()
    ->getNumberFormat()
    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER);

相关问题