zl程序教程

您现在的位置是:首页 >  其他

当前栏目

PHP 导出 Excel 报错: Formula Error: An unexpected error occurred

2023-02-18 16:31:33 时间

1. 问题描述


一个项目中用到了需要将用户信息导出到 Excel ,最初写完测试是正常的,如下图所示

在后来的某一天,导出手机号突然出现了报错,如下图所示

通过提示我们将问题定位在了 B 列 4867 行。

这是因为在 excel 中,单元格中的值如果是以 “=” 开头,则说明这个单元格是根据其他单元格的值算出来的,“=” 后面必须跟着一个合法的表达式。所以,解决方案就是这个单元格的值不让它以 “=” 开头

# Formula Error: An unexpected error occurred 公式错误:发生意外错误
{"code":0,"msg":"用户手机号!B4867 -> Formula Error: An unexpected e

2. 解决方法


找到将值写入到单元格的那行代码,修改前:

$sheet->setCellValueByColumnAndRow(2, $start, $value);

修改后:

if ( $value && strpos($value, '=') === 0 ) {
// 在 = 前面加个单引号
$value = "'" . $value;
}
$sheet->setCellValueByColumnAndRow(2, $start, $value);

现在 Excel 表格就可以正常导出了