首页 > 解决方案 > 我想使用 php 电子表格将数据下载为 CSV 格式

问题描述

    add_action('admin_post_learning_profile_csv_download', 'learning_profile_csv_download');
    function learning_profile_csv_download(){
        $spreadsheet = new Spreadsheet();  
        $Excel_writer = new Xls($spreadsheet);  
        $spreadsheet->setActiveSheetIndex(0);
        $activeSheet = $spreadsheet->getActiveSheet();
        $activeSheet->setCellValue('A1' , 'New file content')->getStyle('A1')->getFont()->setBold(true);  
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. $filename .'.csv"'); 
        header('Cache-Control: max-age=0');
        $Excel_writer->save('php://output');
        $user_id = get_current_user_id();
        echo $user_id;
        echo '<br>';
        $learning_plan = get_user_meta( get_current_user_id(), 'study_guide', true);
        if( empty( $learning_plan ) ) {
            echo 'No Resources Currently Recommended.';
        } else {
            foreach( $learning_plan as $item ) {
                $resource_comps = get_the_terms( $item, 'ivpt_cc' );
                echo get_the_title($item);
                foreach( $resource_comps as $comp ){
                    echo $comp->name;
                    echo'<br>';
                }
            }
        }
    }

这是我的代码,我想将学习计划数据下载为 CSV 格式,分为两列,一次进入标题,另一列用于 comp->name。那么如何在 foreach 循环中设置列和行以进行学习计划呢?

标签: phpwordpressphpspreadsheet

解决方案


对您的 foreach 循环进行一些修改请注意,您不能并行回显任何 html,即带有<br>标签的回显...

希望有帮助

$title = get_the_title($item);
$csv = "";

foreach ( $resource_comps as $comp ){
 $csv .= "'" . $title . "','" . $comp->name . "\r\n";
}
header('Content-type: text/csv');
echo $csv;

推荐阅读