我正在使用 PHP 创建一个 Excel 文档,其中包含从 MySQL 数据库中提取的数据。
在循环遍历末尾的行并将数据打印到每个单元格时,我想将每个具有与 '-1' 等效的字符串/int 的单元格替换为 ' 0'。
这是我到目前为止的代码,
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
$sql = "SELECT * FROM db_table";
$sth = $db->prepare($sql);
$sth->execute();
$filename = date('d.m.Y').'.csv';
$data = fopen($filename, 'w');
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$csv = implode(',', $row) . "\n";
fwrite($data, $csv);
print_r($csv);
}
echo "\r\n";
这可以有效地从数据库获取数据并输出到 Excel 电子表格,但我如何检查提取的每条记录并在记录为 -1 时将其替换为 0?
从视觉上看,如果我的数据库看起来像这样:
id mon tues wed
85 -1 -1 75
36 -1 12 -1
Excel 电子表格将像这样弹出:
85 0 0 75
36 0 12 0
最佳答案
我同意 u_mulder 关于用 0 替换 -1 结果的观点。我将在此基础上进行一些错误检查、缓存清除,并且我将使用 PHP 的 fputcsv 函数将文件直接流式传输到 STDOUT。这将减少内存使用,提高性能,并确保正确解析包含双引号或逗号的字段值。
<?php
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
header("Pragma: no-cache");
header("Expires: 0");
$sql = "SELECT * FROM db_table";
$sth = $db->prepare($sql);
$sth->execute();
$file = fopen('php://output', 'w');
if(false === $file) {
throw new Exception("Failed to create output stream resource.");
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as &$field) {
if("-1" == strval($field)) {
$field = "0";
}
}
if(false === fputcsv($file, $row)) {
throw new Exception("Failed to write row to CSV file.");
}
}
fclose($file);
关于php - 如何在 PHP 中打印到 Excel 电子表格时替换从 MySQL DB 中提取的某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37976617/