1. 程式人生 > >php讀寫Excel/Pdf

php讀寫Excel/Pdf

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


  1. https://github.com/PHPOffice/PHPExcel ↩︎

  2. https://github.com/PHPOffice/PhpSpreadsheet ↩︎