PHP 将 mysql 转换为 excel

标签 php mysql excel

正在将 PHP 转换为 Excel,但在 Excel 文件中遇到问题,它没有在自己的单元格中添加每一行。它的外观如下:https://www.dropbox.com/s/64lz7lqy8z7x72j/export.csv 它把它写入第一个单元格,看起来它已经写入了所有单元格。

enter image description here

这是 PHP 代码:

<?php

$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('chart', $conn) or die(mysql_error($conn));

$result = mysql_query('SELECT * FROM chartgoogle', $conn) or die(mysql_error($conn));

header('Content-Type: text/csv'); // tell the browser to treat file as CSV
header('Content-Disposition: attachment;filename=export.csv'); // tell browser to download a file in user's system with name export.csv

$row = mysql_fetch_assoc($result); // Get the column names
if ($row) {
    outputcsv(array_keys($row)); // It wil pass column names to outputcsv function
}

while ($row) {
    outputcsv($row);    // loop is used to fetch all the rows from table and pass them to outputcsv func
    $row = mysql_fetch_assoc($result);
}

function outputcsv($fields) {
    $separator = '';
    foreach ($fields as $field) {

        echo $separator . $field;
        $separator = ',';        // Separate values with a comma
    }
    echo "\r\n";     //Give a carriage return and new line space after each record
}

?>

最佳答案

试试这个:

function outputcsv($fields) {
    $csv = '';
    foreach ($fields as $field) {
        $csv .= '"' . $field . '",';
    }
    $csv .= "\r\n";     //Give a carriage return and new line space after each record
    echo $csv;
}

查看字段前后的双引号。 CSV 文件通常使用双引号作为闭包。他们称之为文本限定符。

关于PHP 将 mysql 转换为 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554464/

相关文章:

php - 聊天应用程序的数据库设计

php - 除非我刷新页面,否则数据不会插入数据库?

php - 我怎样才能以更快的方式做到这一点?

php json_encode mysql 结果

java - 使用 Apache POI、Excel 和 Eclipse 时出现 "Exception in thread "main "java.lang.NullPointerException"?

VBA 群发邮件问题

php - 添加 WHERE、SELECT、ORDER BY 等...就像通过 PHP 的链式 SQL

php - 在 mysql 中搜索并回显多个结果

PHP 不会隐藏 mysql_*() 警告,即使调用了 error_reporting(0)

excel - 语法错误CountIfs函数多个条件