简体   繁体   中英

Export to Excel is dropping leading zero

I found this code on web for export tables from Mysql to Excel. The problem is that data exported to excel is missing the leading zero. So instead of number 090888 i get 90888. Except that code work fine, so i would like to change this particular code.

If anyone can help with this I would really appreciate it.

The code:

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";
    }
?>

When you print it into the excel sheet, precede the numbers by a single quote. That will force them to be treated as text, and not as numeric data.

For example, print '090888 instead of just 090888 , which will force it to treat it as a string (but will not display the ' in excel.

Another way would be to adjust formatting, but I don't think that is possible in the above case.

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

After using PHPEXCEL, use like this:

$objPHPExcel->getActiveSheet()
    ->setCellValueExplicit("$row[$j]", "value" ,PHPExcel_Cell_DataType::TYPE_STRING);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM