zl程序教程

您现在的位置是:首页 >  工具

当前栏目

PhpSpreadsheet读取excel「建议收藏」

Excel 建议 收藏 读取 PhpSpreadsheet
2023-06-13 09:13:38 时间

大家好,又见面了,我是你们的朋友全栈君。

PhpSpreadsheet

安装

	composer require phpoffice/phpspreadsheet

支持的格式

是否支持读

是否支持写

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 (依赖安装 TCPDF, Dompdf 或 mPDF 库)

源文档

compress.xlsx 文件

php读取

<?php
require "vendor/autoload.php";
// $inputFileName = 'source.xlsx';
$inputFileName = 'compress.xlsx';
$sheetname = 'Sheet1';
/** 1.检测文件类型 **/
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
/** 2.根据类型创建合适的读取器对象 **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
// 3. 设置读取器选项
// $reader->setReadDataOnly(true);
$reader->setLoadSheetsOnly($sheetname);
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{ 

public function readCell($column, $row, $worksheetName = '')
{ 

// 选定区域
if ($row >= 1 && $row <= 7) { 

if (in_array($column, range('A','B'))) { 

return true;
}
}
return false;
}
}
$filterSubset = new MyReadFilter();
// 使用过滤器
$reader->setReadFilter($filterSubset);
// 4.读取表格表对象
$spreadsheet = $reader->load($inputFileName);
// 5. 得到工作表
$workSheet = $spreadsheet->getActiveSheet();
// 6. 读取表格内容
$cellA1 = $workSheet->getCell('A1');
echo 'Value: ', $cellA1->getValue(), '; Address: ', $cellA1->getCoordinate(), PHP_EOL;
// 7.超出范围不读取
$cellA9 = $workSheet->getCell('A9');
echo 'Value: ', $cellA9->getValue(), '; Address: ', $cellA9->getCoordinate(), PHP_EOL;

测试

D:\code-base\php\pkg_test>php "d:\code-base\php\pkg_test\xlsx.php"
Value: age; Address: A1
Value: ; Address: A9

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/192425.html原文链接:https://javaforall.cn