首页 > 编程 > PHP > 正文

使用phpexcelreader读取excel文件

2020-03-22 18:05:14
字体:
来源:转载
供稿:网友
  • 有时候如果有大量的数据需要导入到数据库,最低级的办法就是,一个一个的手动添加,而日常生活中,常常用表格来记录,能不能让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:读取完毕后,会将表格有关的信息,全部存到一个大数组中。

    <?phperror_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:如果要读取,数组中的详细内容,给出几个例子

    <?phperror_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);

    <?phperror_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编程

    郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表