在流式传输到xls之前将csv转换为xls

时间:2015-05-27 11:51:50

标签: php

我将自定义WordPress帖子类型输出到CSV。工作得很好...现在我必须输出到xls ...我想使用PHPExcel ...我不知道如何实现这个,因为我的代码流一个(csv)文件。我如何转换csv并流式传输生成的xls ...到目前为止我的代码:

// create a new array of values that reorganizes them in a new multidimensional array where each sub-array contains all of the values for one custom post instance
    $ccsve_generate_value_arr_new = array();

    foreach($ccsve_generate_value_arr as $value) {
           $i = 0;
           while ($i <= ($ccsve_count_posts-1)) {
             $ccsve_generate_value_arr_new[$i][] = $value[$i];
            $i++;
        }
    }

    // build a filename
//  $ccsve_generate_csv_filename = $ccsve_generate_post_type.'-'.date('Ymd_His').'-export.csv';
    $ccsve_generate_csv_filename = 'WPhonden.csv';

    //output the headers for the CSV file
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$ccsve_generate_csv_filename}");
    header("Expires: 0");
    header("Pragma: public");

    //open the file stream
    $fh = @fopen( 'php://output', 'w' );

    $headerDisplayed = false;

    foreach ( $ccsve_generate_value_arr_new as $data ) {
    // Add a header row if it hasn't been added yet -- using custom field keys from first array
    if ( !$headerDisplayed ) {
        fputcsv($fh, array_keys($ccsve_generate_value_arr));
        $headerDisplayed = true;
    }

    // Put the data from the new multi-dimensional array into the stream
    fputcsv($fh, $data);
}

// Close the file stream
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;
    }

这是PHPExcel代码:

include 'PHPExcel/IOFactory.php';

$objReader = PHPExcel_IOFactory::createReader('CSV');

// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
$objReader->setDelimiter("\t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
$objReader->setInputEncoding('UTF-16LE');

$objPHPExcel = $objReader->load('MyCSVFile.csv');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('MyExcelFile.xls');

0 个答案:

没有答案
相关问题