创建不带库的Excel文件

时间:2019-10-26 18:45:39

标签: php excel

我使用以下代码:

header( "Content-Type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=liste.xls");

echo "\xEF\xBB\xBF";

然后我像这样在while循环中写入SQL数据:

echo "\n<table><tr><td>".$first[$post_a]."</td>\t<td>".$second[$post_a]."</td>\t<td>".$third[$post_a]."</td>\t</td></tr></table>";

当我尝试打开此创建的文件时,excel会说版本和类型都处于取消匹配状态,即使这样我也可以在桌面上打开此警告后打开文件,但是当我尝试在手机上打开时,警告后无法打开文件。

1 个答案:

答案 0 :(得分:0)

您需要在此处输入类似内容。在for循环中也忽略我的逻辑,可能要使用自己的。

    $filename = "export_".date("m-d-Y_hia") . ".csv";
    ob_end_clean();
    $fp = fopen($filename,"w");

    $is_header = true;

    $no_meta_appnd = array('SKU','Name','Publish','Categories','Description');

    foreach ($res as $index => $product){
        $arr = array();

        if($is_header){ // put all the header in array
            foreach ($product as $index => $p){
                if(in_array($index,$no_meta_appnd)){
                    array_push($arr,$index);
                }else{
                    array_push($arr,"Meta: ".$index);
                }
            }
            $is_header = false;
            fputcsv($fp,$arr);  // add headers
            $arr = array();     // empty out array for first row
            foreach ($product as $index => $p){
                array_push($arr,$p);
            }
            fputcsv($fp,$arr);  // add first row after header
        }else{
            foreach ($product as $index => $p){
                array_push($arr,$p);
            }
            fputcsv($fp,$arr);  // rest of the rows
        }
    }
//unserialize();
    fclose($fp);

// download
//    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$filename);
    header("Content-Type: application/csv; ");
    header('Pragma: no-cache');

    readfile($filename);

// deleting file
    unlink($filename);
    exit();