如何将数据从MySQL导出到Excel(.xlsx),但在导出之前处理数据

我正在尝试将数据从MySQL导出到xlsx,但是在我的数据库中可能会有一些0和1而不是实际数据。让我更好地解释一下:有一个列用于设置白天还是晚上,但白天使用0,夜晚使用1。当我使用下面的代码导出时,我得到一个带有这些0和1的xlsx。


已经尝试过的东西,例如https://phppot.com/php/database-data-export-to-excel-file-using-php/和https://artisansweb.net/how-to-export-mysql-database-data -to-excel-using-php /但在发送之前我无法编辑xlsx的内容


 $filename = "Export_excel.xls";

    header("Content-Type: application/vnd.ms-excel");

    header("Content-Disposition: attachment; filename=\"$filename\"");

    $isPrintHeader = false;

    if (! empty($productResult)) {

        foreach ($productResult as $row) {

            if (! $isPrintHeader) {

                echo implode("\t", array_keys($row)) . "\n";

                $isPrintHeader = true;

            }

            echo implode("\t", array_values($row)) . "\n";

        }

    }

当代码看到零时,我想将其设置为“ day”


慕田峪9158850
浏览 403回答 2
2回答

holdtom

如果只想显示特定字段。从您的表中选择id,name,(case table when table_column = 0 THEN'day'when table_column = 1 THEN'night'END)作为table_column输出看起来像:编号名称table_column

慕码人8056858

首先,您的脚本创建一个制表符分隔的纯文本,其中Excel为mime-type。这不是真正的Excel文件,可能会给您带来意想不到的结果。如果要创建真实的Excel文件,请使用类似PHPSpreadsheet的文件。尽管如此,您可以像在他的注释中推荐的Saji一样更改您的SQL查询,也可以在foreach语句中执行以下操作:if($row['header_name'] == 0){    $row['header_name'] = 'day';}else{    $row['header_name'] = 'night';}请注意,您必须在数组中使用键,而不是在脚本中也用作列名的“ header_name”。
打开App,查看更多内容
随时随地看视频慕课网APP