开发者

Export from PHP to Excel

开发者 https://www.devze.com 2023-01-22 05:09 出处:网络
I need to export data from php to Excel, and be able to format various items in the excel spreadsheet.

I need to export data from php to Excel, and be able to format various items in the excel spreadsheet.

So far, the best library that I have found is PHPExcel. However, it seems very heavy, and somewhat slow. Granted, it is very powerful.

Is there anything a bit more lightweight and faster, that allows me to export to excel and开发者_运维技巧 be able to apply simple formatting (bold, alignment, borders)?


I just got done with this yesterday. Using PHPExcel, I had no problems reading in a "master" document with formatting, writing 20-100 rows of content, and saving off the file (I save it "to screen" for immediate download. While some people on the forums complained about speed and overhead, I'm pushing a lot of data its way and it doesn't have any problem at all doing what it advertises.

Note that somewhere I read to do styling in series as opposed to in loops when possible. For example, style a1:a50 as opposed to style->a1, style->a2 in a loop. Apparently, the two different scenarios have very different memory implications.

The only gotcha I found was a few quirks between outputting and reading Excel 2003 files. If you're working entirely in XLSX files, it should function exactly as documented.


Here is simple Excel file generation function, very fast and exactly .xls file.

$filename = "sample_php_excel.xls";
$data = array(
array("User Name" => "Abid Ali", "Q1" => "$32055", "Q2" => "$31067", "Q3" => 32045, "Q4" => 39043),
array("User Name" => "Sajid Ali", "Q1" => "$25080", "Q2" => "$20677", "Q3" => 32025, "Q4" => 34010),
array("User Name" => "Wajid Ali", "Q1" => "$93067", "Q2" => "$98075", "Q3" => 95404, "Q4" => 102055),
);
to_xls($data, $filename);

function to_xls($data, $filename){
$fp = fopen($filename, "w+");
$str = pack(str_repeat("s", 6), 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); // s | v
fwrite($fp, $str);
if (is_array($data) && !empty($data)){
    $row = 0;
    foreach (array_values($data) as $_data){
        if (is_array($_data) && !empty($_data)){
            if ($row == 0){
                foreach (array_keys($_data) as $col => $val){
                    _xlsWriteCell($row, $col, $val, $fp);
                }
                $row++;
            }
            foreach (array_values($_data) as $col => $val){
                _xlsWriteCell($row, $col, $val, $fp);
            }
            $row++;
        }
    }
}
$str = pack(str_repeat("s", 2), 0x0A, 0x00);
fwrite($fp, $str);
fclose($fp);
}

function _xlsWriteCell($row, $col, $val, $fp){
if (is_float($val) || is_int($val)){
    $str  = pack(str_repeat("s", 5), 0x203, 14, $row, $col, 0x0);
    $str .= pack("d", $val);
} else {
    $l    = strlen($val);
    $str  = pack(str_repeat("s", 6), 0x204, 8 + $l, $row, $col, 0x0, $l);
    $str .= $val;
}
fwrite($fp, $str);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号