码迷,mamicode.com
首页 > Web开发 > 详细

使用php-excel-reader读取excel文件

时间:2016-06-28 14:33:06      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

        有时候如果有大量的数据需要导入到数据库,最低级的办法就是,一个一个的手动添加,而日常生活中,常常用表格来记录,能不能让PHP直接读取一个excel表格,然后,将表格中的内容,全部导入数据库呢,这样子,可以节省大量的时间。

        php-excel-reader是一个读取excel的类,可以很轻松的使用它读取excel文件。


        首先要下载有关的文件:

        链接:http://pan.baidu.com/s/1i5990hv 密码:4npd

技术分享

        其余文件为事例文件,请认真分析源码。

表格对应内容:

技术分享

1:引入类,创建对象,设置读取文件的目录

<?php 
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader();//创建对象
$data->setOutputEncoding('UTF-8');//设置编码格式
$data->read("example.xls");//读取excel文档

2:读取完毕后,会将表格有关的信息,全部存到一个大数组中。

<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader();//创建对象
$data->setOutputEncoding('UTF-8');//设置编码格式
$data->read("example.xls");//读取excel文档
echo "<pre>";
print_r($data->sheets);
echo "</pre>";

运行结果如下
技术分享

3:如果要读取,数组中的详细内容,给出几个例子

<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader();//创建对象
$data->setOutputEncoding('UTF-8');//设置编码格式
$data->read("example.xls");//读取excel文档
//echo "<pre>";
//print_r($data->sheets);
//echo "</pre>";

echo $data->sheets[0]['numRows']."行<br>";//读出一共几行
echo $data->sheets[0]['numCols']."列<br>";//读出一共几列
echo $data->sheets[0]['cells'][1][1]."<br>";//读出第一行第一列的内容
print_r($data->sheets[0]['cells'][1]);//第一行的数据
echo "<br>";
echo implode(",",$data->sheets[0]['cells'][1])."<br>";//去除第一行的数据,每个中间添加分隔符
for($i=1;$i<=$data->sheets[0]['numCols'];$i++)//一次读出第一行的所有数据
{
	echo $data->sheets[0]['cells'][1][$i]." ";
}
echo "<br>";
echo "<br>";

//读出所有数据

for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
  //$data->sheets[0]['numCols']为Excel列数
  for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
   //显示每个单元格内容
   echo $data->sheets[0]['cells'][$i][$j].'  ';
  }
  echo '<br>';
}

技术分享



注意上述,echo implode(",",$data->sheets[0][‘cells‘][1])."<br>";//去除第一行的数据,每个中间添加分隔符,,的应用,这样就可以,直接向数据库插入一整行的数据了



注:

dump(),它可以将excel内容以html格式输出:

echo $data->dump(true,true);

<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("example.xls");
?>
<html>
<head>
<style>
table.excel {
	border-style:ridge;
	border-width:1;
	border-collapse:collapse;
	font-family:sans-serif;
	font-size:12px;
}
table.excel thead th, table.excel tbody th {
	background:#CCCCCC;
	border-style:ridge;
	border-width:1;
	text-align: center;
	vertical-align:bottom;
}
table.excel tbody th {
	text-align:center;
	width:20px;
}
table.excel tbody td {
	vertical-align:bottom;
}
table.excel tbody td {
    padding: 0 3px;
	border: 1px solid #EEEEEE;
}
</style>
</head>
<body>
<?php echo $data->dump(true,true); ?>
</body>
</html>

技术分享







使用php-excel-reader读取excel文件

标签:

原文地址:http://blog.csdn.net/qq_28602957/article/details/51775341

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!