1

我在网上找到了这段代码,用于将表从 Mysql 导出到 Excel。问题是导出到 excel 的数据缺少前导零。所以我得到的是 90888 而不是数字 090888。除了代码工作正常,所以我想更改这个特定的代码。

如果有人可以提供帮助,我将不胜感激。

编码:

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");

/*******Start of Formatting for Excel*******/

//define separator (defines columns in excel & tabs in word)

$sep = "\t"; //tabbed character

//start of printing column names as names of MySQL fields

for ($i = 0; $i < mysql_num_fields($result); $i++) {

echo mysql_field_name($result,$i) . "\t";

}

print("\n");

//end of printing column names

//start while loop to get data

    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";

        for($j=0; $j<mysql_num_fields($result);$j++)

        {

            if(!isset($row[$j]))

                $schema_insert .= "NULL".$sep;

            elseif ($row[$j] != "")

                $schema_insert .= "$row[$j]".$sep;

            else

                $schema_insert .= "".$sep;

        }

        $schema_insert = str_replace($sep."$", "", $schema_insert);

 $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);

        $schema_insert .= "\t";

        print(trim($schema_insert));

        print "\n";
    }
?>
4

3 回答 3

0

You can't add the '0' for integer when creating XLS. because the format of the column is integer only in the Excel you have created. so we need to change the format of the column. for this you can use this package PHPEXCEL for creating Excel.

and also you can refer this post:

https://stackoverflow.com/a/3269351/1638375

于 2012-10-22T09:50:28.467 回答
0

使用 PHPEXCEL 后,像这样使用:

$objPHPExcel->getActiveSheet()
    ->setCellValueExplicit("$row[$j]", "value" ,PHPExcel_Cell_DataType::TYPE_STRING);
于 2013-02-05T03:52:55.187 回答
0

当您将其打印到 Excel 工作表中时,请在数字前加上单引号。这将迫使它们被视为文本,而不是数字数据。

例如, print'090888而不是 just 090888,这将强制它将其视为字符串(但不会'在 excel.

另一种方法是调整格式,但我认为在上述情况下这是不可能的。

于 2012-10-22T09:13:29.120 回答