php读取EXCEL文件 php excelreader读取excel文件
php开发中肯定会遇到将excel文件内容导入到数据库的需要,php-excel-reader是一个读取excel的类,可以很轻松的使用它读取excel文件非常方便。php-excel-reader下载地址: //www.jb51.net/codes/67223.html
我下载的是php-excel-reader-2.21版本,使用的时候还遇到几个小问题,后面再细说,先奉上php实例:
我使用的excel如下图:
<?php
/*by www.phpddt.com*/
header("Content-Type:text/html;charset=utf-8");
require_once 'excel_reader2.php';
//创建对象
$data = new Spreadsheet_Excel_Reader();
//设置文本输出编码
$data->setOutputEncoding('UTF-8');
//读取Excel文件
$data->read("example.xls");
//$data->sheets['numRows']为Excel行数
for ($i = 1; $i <= $data->sheets['numRows']; $i++) {
//$data->sheets['numCols']为Excel列数
for ($j = 1; $j <= $data->sheets['numCols']; $j++) {
//显示每个单元格内容
echo $data->sheets['cells'][$i][$j].' ';
}
echo '<br>';
}
?>
再来说说这个类的小问题:
(1)出现Deprecated: Function split() is deprecated in 。。。错误
解决:将excel_reader2.php源码中split改为explode,详情点击php中explode与split的区别介绍
(2)出现Deprecated: Assigning the return value of new by reference is deprecated in错误
解决:将excel_reader2.php源码中$this->_ole =& new OLERead()中 &去掉,因为php5.3中废除了=& 符号直接用=引用
(3)乱码问题解决:
构造函数是function Spreadsheet_Excel_Reader($file='',$store_extended_info=true,$outputEncoding=''),它默认的编码是utf-8,如果不指定,可能会出现乱码问题,可通过$data->setOutputEncoding('GBK');指定,还有如果你使用dump()函数,dump()函数将excel内容一html格式输出,使用htmlentities将字符转化为html的,它默认使用ISO8559-1编码的,所以你要将 excel_reader2.php源码中 htmlentities($val)函数改为htmlentities($val,ENT_COMPAT,"GB2312");才行。
最后来说说,php-excel-reader操作excel中的两个重要的方法:
1.dump(),它可以将excel内容以html格式输出:
echo $data->dump(true,true);
2.将excel数据存入数组中,使用$data->sheets,打印下如下:
Array
(
=> Array
(
=> 0
=> 0
=> 5
=> 4
=> Array
(
=> Array
(
=> 编号
=> 姓名
=> 年龄
=> 学号
)
=> Array
(
=> 1
=> 小红
=> 22
=> a1000
)
=> Array
(
=> 2
=> 小王
=> 33
=> a1001
)
=> Array
(
=> 3
=> 小黑
=> 44
=> a1002
)
=> Array
(
=> by
=> www.phpddt.com
)
)
=> Array
(
=> Array
(
=> Array
(
=> 15
)
=> Array
(
=> 15
)
=> Array
(
=> 15
)
=> Array
(
=> 15
)
)
=> Array
(
=> Array
(
=> 1
=> 1
=> unknown
=> %s
=> 0
=> 0
=>
=> 15
)
=> Array
(
=> 15
)
=> Array
(
=> 22
=> 22
=> unknown
=> %s
=> 0
=> 0
=>
=> 15
)
=> Array
(
=> 15
)
)
=> Array
(
=> Array
(
=> 2
=> 2
=> unknown
=> %s
=> 0
=> 6
=>
=> 23
)
=> Array
(
=> 23
)
=> Array
(
=> 33
=> 33
=> unknown
=> %s
=> 0
=> 6
=>
=> 23
)
=> Array
(
=> 23
)
)
=> Array
(
=> Array
(
=> 3
=> 3
=> unknown
=> %s
=> 0
=> 0
=>
=> 15
)
=> Array
(
=> 15
)
=> Array
(
=> 44
=> 44
=> unknown
=> %s
=> 0
=> 0
=>
=> 15
)
=> Array
(
=> 15
)
)
=> Array
(
=> Array
(
=> 15
)
=> Array
(
=> 24
=> Array
(
=> 23
=> www.phpddt.com
=> http://www.phpddt.co
)
)
)
)
)
=> Array
(
=> 0
=> 0
=> 0
=> 0
)
=> Array
(
=> 0
=> 0
=> 0
=> 0
)
)
页:
[1]