如何使用php / mysql强制将Integer-to-String导出到Excel?

时间:2017-09-14 01:25:23

标签: php mysql excel

我需要将MySql表中的所有数据导出到excel。我使用下面的代码,工作正常。

问题是:有2个字段是30个以上的整数。因此,当我将其导出到.csv文件时,excel会将它们转换为科学记数法。

示例:字段" 95145612345641859415634194164163"转换为" 9.51456E + 31"

如何强制它将其作为字符串读取?

<?php


exportMysqlToCsv('export_csv.csv');



function exportMysqlToCsv($filename = 'export_csv.csv')
{

   $conn = dbConnection();

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT * FROM cadastros";


    $result = $conn->query($sql_query);

    $f = fopen('php://temp', 'wt');
    $first = true;
    while ($row = $result->fetch_assoc()) {
        if ($first) {
            fputcsv($f, array_keys($row));
            $first = false;
        }
        fputcsv($f, $row);
    } // end while

    $conn->close();

    $size = ftell($f);
    rewind($f);

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: $size");
    header("Content-type: text/x-csv");
    header("Content-type: text/csv");
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    fpassthru($f);
    exit;

}

// db connection function
function dbConnection(){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "creche_escolas";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    return $conn;
}

3 个答案:

答案 0 :(得分:0)

插入值时,您应该确保您的号码是一个字符串,请尝试:

fputcsv($f, ['12343231743986248756324354595', '123456', 12123437829564329758623456789]);

第一个值将保持不变,而最后一个值将转换为1.21234378296E+28

因此,您需要使用函数替换行fputcsv($f, $row);以转换为number_format等字符串:

fputcsv($f, array_map(function($v){return number_format($v, 0, '', '');}, $row));

答案 1 :(得分:0)

我的逻辑工作正常,请在导出大量excel时使用它 首先,确定条件是否适合您,并在字符串中使用逗号“'”

public login(email: string, password: string) {
    return this.http.post(GlobalUrl, {user: { email: email, password: password }}, this.httpOptions).subscribe((response: HttpResponse<any>) =>{
        console.log(response);
    });
}

导出Excel文件后。再次将逗号“”替换为“”。您的excel文件单元格可以正常使用

谢谢。

答案 2 :(得分:0)

我的逻辑工作正常,请在使用excel导出大量数字时使用此函数,如果条件适合您,请首先使用,并在字符串中使用逗号“'” $ large_number =“'”。(字符串)$ data-> orders_id; 导出Excel文件后。再次将逗号“”替换为“”。您的excel文件单元格会很好,谢谢您