PHPExcel taking an extremely long time to read Excel file

后端 未结 4 704
礼貌的吻别
礼貌的吻别 2021-01-14 08:11

I\'m using PHPExcel 1.7.8, PHP 5.4.14, Windows 7, and an Excel 2007 spreadsheet. The spreadsheet consists of 750 rows, columns A through BW, and is about 600KB in size. This

4条回答
  •  天命终不由人
    2021-01-14 08:20

    If you know your file is a pretty plain excel file, you can do manual reading. A .xslx file is just a zip archive with the spreadsheet values and structure stored into xml files. This script took me from the 60 seconds used on PHPExcel down to 0.18 seconds.

    $zip = new ZipArchive();
    $zip->open('path_to/file.xlsx');
    $sheet_xml = simplexml_load_string($zip->getFromName('xl/worksheets/sheet1.xml'));
    $sheet_array = json_decode(json_encode($xml), true);
    $values = simplexml_load_string($zip->getFromName('xl/sharedStrings.xml'));
    $values_array = json_decode(json_encode($values), true);
    
    $end_result = array();
    if ($sheet_array['sheetData']) {
        foreach ($sheet_array['sheetData']['row'] as $r => $row) {
            $end_result[$r] = array();
            foreach ($row['c'] as $c => $cell) {
                if (isset($cell['@attributes']['t'])) {
                    if ($cell['@attributes']['t'] == 's') {
                        $end_result[$r][] = $values_array['si'][$cell['v']]['t'];
                    } else if ($cell['@attributes']['t'] == 'e') {
                        $end_result[$r][] = '';
                    }
                } else {
                    $end_result[$r][] = $cell['v'];
                }
            }
        }
    }
    

    Result:

    Array
    (
        [0] => Array
            (
                [0] => A1
                [1] => B1
                [2] => C1
            )
    
        [1] => Array
            (
                [0] => A2
                [1] => B2
                [2] => C2
            )
    )
    

    This is error prone and not optimized, but it works and illustrates the basic idea. If you know your file, then you can make reading very fast. If you allow users to input the files, then you should maybe avoid it - or at least do the neccessary checks.

提交回复
热议问题