php讀寫Excel/Pdf
阿新 • • 發佈:2018-12-03
PHPExcel1已經廢棄,現在用PhpSpreadsheet2,官方文件。
PhpSpreadsheet是一個用純PHP寫的類庫,可以讀寫操作不同的電子表格檔案格式,像Excel和LibreOffice。
支援的文件格式:
Format | Reading | Writing |
---|---|---|
Open Document Format/OASIS (.ods) | ✓ | ✓ |
Office Open XML (.xlsx) Excel 2007 and above | ✓ | ✓ |
BIFF 8 (.xls) Excel 97 and above | ✓ | ✓ |
BIFF 5 (.xls) Excel 95 | ✓ | |
SpreadsheetML (.xml) Excel 2003 | ✓ | |
Gnumeric | ✓ | |
HTML | ✓ | ✓ |
SYLK | ✓ | |
CSV | ✓ | ✓ |
PDF (using either the TCPDF, Dompdf or mPDF libraries, which need to be installed separately) | ✓ |
示例,建立第一個xlsx文件
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
讀取Excel
use PhpOffice\PhpSpreadsheet\IOFactory;
// $inputFileName 也可以是表單上傳的$_FILES['file']['tmp_name']
$inputFileName = __DIR__ . '/sampleData/example1.xls';
$spreadsheet = IOFactory::load($inputFileName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
var_dump($sheetData);
更多讀取Excel見Reader