douzi8548 2013-01-04 18:02
浏览 38
已采纳

阻止MS Excel使用PHP 5.3剥离前导零

I have the following sample line in a CSV file I am generating with PHP. When I cat the file this is what I see:

541787,271561,"04/01/2013 09:26:35",18801872,Many,"PINSTRIPE JACKET",18806821872,75.00,GBP,1,0078,5051916991872

However, when I open this file in MS Excel the "0078" has been changed to "78" - so MS Excel has taken it upon itself to strip the leading zeros. It has also converted the EAN13 number (in Column L) to an exponent.

Stripped Zeros

In terms of the PHP code I am outputting the file to the browser with the following code, which works in principal, but I would like to know if there is a way to control the stripping of the leading zeros with PHP?

// set the headers
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=_report_' . date('Y-m-d-His') . '.csv');
header('Pragma: no-cache');

echo $report->getCSVOutput();
exit;    
  • 写回答

4条回答 默认 最新

  • drdl18946 2013-01-08 12:21
    关注

    It turns out that with a small tweak (as suggested by the owner) to SimpleExcel this package can handle the stripping of leading zeros.

    I am using the code below:

    /**
     * get the order data in Microsoft Excel XML format (to be used when output to the browser directly)
     * @return void
     */
    public function getExcelXMLOutput() {
    
        // instantiate new object (will automatically construct the parser & writer type as XML)
        $excel = new SimpleExcel('xml');                    
    
        // add some data to the writer
        $excel->writer->setData($this->orders);                                                 
    
        // save the file with specified name
        // and specified target (default to browser)           
        $excel->writer->saveFile('report_' . date('Y-m-d-His'));
    
    }
    

    The code amendment required me to change the XMLWriter class in the addRow method to:

    $datatype = is_string($val) ? 'String' : (is_numeric($val) ? 'Number' : 'String');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?