php读写Excel/Pdf

葛晔
2023-12-01

PHPExcel1已经废弃,现在用PhpSpreadsheet2官方文档

PhpSpreadsheet是一个用纯PHP写的类库,可以读写操作不同的电子表格文件格式,像Excel和LibreOffice。

支持的文档格式:

FormatReadingWriting
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 ↩︎

 类似资料: