导入 xlsx php,php如何使用phpexcel类导入excel表格数据

第一步:我们要去官网下载phpexcel类文件。

第二步:我们要先自己模拟一个xlsx格式的文件。

我这里就新建一个123.xlsx文件。注意,文件名最好不要使用中文,如果是中文的话,建议先重命名成英文文件名。

有朋友会问问什么不用中文,因为程序遇到中文总会出现一些意想不到的问题,比如乱码就是很头疼的事情。

e37e0571e253085f5526f660dee0839f.png

第三步:我们直接看看在代码中,是怎么实现php导入excel的。

header("Content-type:text/html;charset=utf-8"); // 设置字符编码

require_once './phpexcel/PHPExcel.php'; // 引入phpexcel库文件

$filename = './123.xlsx'; // 文件地址

$PHPExcel = \PHPExcel_IOFactory::load($filename);// 读取excel文件

$currentSheet = $PHPExcel->getSheet(0); // 第一个sheet

$col = $currentSheet->getHighestColumn(); // 取得总列数

$row = $currentSheet->getHighestRow(); // 取得总行数

$arr = array();

for ($currentRow = 1; $currentRow <= $row; $currentRow++) {

for ($currentColumn = 'A'; $currentColumn <= $col; $currentColumn++) {

$arr[$currentRow][] .= $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue();

}

}

print_r($arr);

输出之后的效果:

Array

(

[1] => Array

(

[0] => 小明

[1] => 18012345678

[2] => 安徽

[3] => 18

)

[2] => Array

(

[0] => 小黑

[1] => 13212345678

[2] => 北京

[3] => 20

)

[3] => Array

(

[0] => 小华

[1] => 15252341235

[2] => 上海

[3] => 32

)

[4] => Array

(

[0] => 小白

[1] => 18112345678

[2] => 江苏

[3] => 21

)

[5] => Array

(

[0] => 小红

[1] => 13312345678

[2] => 福建

[3] => 19

)

)

值得注意的是:

ord($currentColumn) - 65

在这里你要转化一下ASCII值,不然你读取不到第二列的值。

通过上面的几行代码,可以轻松的实现php导入excel的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值