如何在函数内使用PHPSpreadsheet类

时间:2019-06-18 11:32:46

标签: php wordpress phpspreadsheet

我创建了一个AJAX函数,该函数在前端的click事件上运行。在此函数内部,我希望能够生成XLS电子表格,但在函数内部无法执行此操作。我相信这与我在函数外部声明use语句有关,或者该函数无法访问类?我尝试在函数中将它们声明为declair,但出现此错误;

syntax error, unexpected 'use'

有人对此有解决方案吗?这是我的代码;

add_action('wp_ajax_nopriv_campaign', 'email_campaign');
add_action('wp_ajax_campaign', 'email_campaign');

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

function email_campaign(){
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', 'Hello World !');
    $writer = new Xlsx($spreadsheet);
    $writer->save('hello world.xlsx');

    die();
}

这是我的函数调用方式;

$('#campaign_form').submit(function(e){
    e.preventDefault();

    $.ajax({
        url: ajax_url,
        type: 'post',
        dataType: 'json',
        data: { 
            action: 'campaign'
        },
        error : function(response){
            console.log(response);
        },
        success : function(response){
            console.log(response);
        }
    });
});

1 个答案:

答案 0 :(得分:0)

将代码修改为:

require_once 'vendor/autoload.php';

function email_campaign(){
    $path = dirname(__DIR__).'/sheets';
    $fileName = 'hello_world.xlsx';

    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', 'Hello World !');
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save($path.'/'.$fileName);
}