programing

php 스프레드시트 라이브러리를 사용하여 배열에서 시트로 데이터 쓰기

oldcodes 2023. 6. 8. 22:31
반응형

php 스프레드시트 라이브러리를 사용하여 배열에서 시트로 데이터 쓰기

다음을 사용하여 배열에서 Excel 시트 열 헤더를 작성하는 방법phpspreadsheet도서관?

아래는 제가 시도하고 있지만 작동하지 않는 코드입니다.

    // $header is an array containing column headers
    $header = array("Customer Number", "Customer Name", "Address", "City", "State", "Zip");
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->fromArray($header, NULL, 'A1');     

    // redirect output to client browser
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');

당신은 글을 써야 합니다.

$sheet->fromArray([$header], NULL, 'A1');

또한 잘못된 Content-Type 헤더를 가지고 있습니다...


BIFF .xls 파일의 경우

application/vnd.ms-excel

Excel 2007 이상의 .xlsx 파일의 경우

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

따라서 완전하게 작동하는 코드는 다음과 같습니다.

    // $header is an array containing column headers
    $header = [array("Customer Number", "Customer Name", "Address", "City", "State", "Zip")];

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->fromArray($header, NULL, 'A1');     

    // redirect output to client browser
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');

자세한 내용이 포함된 예제

$database = [
    [ 'Tree',  'Height', 'Age', 'Yield', 'Profit' ],
    [ 'Apple',  18,       20,    14,      105.00  ],
    [ 'Pear',   12,       12,    10,       96.00  ],
    [ 'Cherry', 13,       14,     9,      105.00  ],
    [ 'Apple',  14,       15,    10,       75.00  ],
    [ 'Pear',    9,        8,     8,       76.80  ],
    [ 'Apple',   8,        9,     6,       45.00  ],
];

$criteria = [
    [ 'Tree',      'Height', 'Age', 'Yield', 'Profit', 'Height' ],
    [ '="=Apple"', '>10',    NULL,  NULL,    NULL,     '<16'    ],
    [ '="=Pear"',  NULL,     NULL,  NULL,    NULL,     NULL     ],
];

$worksheet->fromArray( $criteria, NULL, 'A1' )
    ->fromArray( $database, NULL, 'A4' );

$worksheet->setCellValue('A12', '=DCOUNT(A4:E10,"Height",A1:B3)');

$retVal = $worksheet->getCell('A12')->getCalculatedValue();

// $retVal = 3

더 좋은 예들이 있습니다. https://phpspreadsheet.readthedocs.io/en/latest/topics/calculation-engine/ #http_1

네임스페이스를 포함해야 합니다.

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

언급URL : https://stackoverflow.com/questions/48681839/write-data-from-array-to-sheet-using-phpspreadsheet-library

반응형