PHPExcel的使用方法

来源:互联网 发布:ubuntu上安装mysql 编辑:程序博客网 时间:2024/06/16 17:17

首先需要申明的是,直接用会报错,则个文件很多地方都有问题,我这个是更正过后的效果。更正过程请参考:

http://blog.csdn.net/zhezhebie/article/details/76974534

下面直接列出使用方法:

<?php//屏蔽所有错误error_reporting(0);require_once 'Excel/reader.php';$data = new SpreadsheetExcelReader();// Set output Encoding.$data->setOutputEncoding('utf-8');//测试你要打开的xls文件,自带的那个cvs文件已经损坏,这是我用WPS编写的一个xls文件,就正常编辑$data->read('test.xls');// 表的行数$numRows = $data->sheets[0]['numRows'];//表的列数$numCols = $data->sheets[0]['numCols'];//表里面的数据,二维数组格式echo "<pre>";print_r($data->sheets[0]['cells']);echo "</pre>";exit;

效果图:
这里写图片描述

说明:

/*$data->sheets[0]['numRows'] - count rows$data->sheets[0]['numCols'] - count columns$data->sheets[0]['cells'][$i][$j] - data from $i-row $j-column$data->sheets[0]['cellsInfo'][$i][$j] - extended info about cell$data->sheets[0]['cellsInfo'][$i][$j]['type'] = "date" | "number" | "unknown"if 'type' == "unknown" - use 'raw' value, because  cell contain value with format '0.00';$data->sheets[0]['cellsInfo'][$i][$j]['raw'] = value if cell without format$data->sheets[0]['cellsInfo'][$i][$j]['colspan']$data->sheets[0]['cellsInfo'][$i][$j]['rowspan'] */

复杂的例子:
批量导入n个excel文件数据到数据库。

<?php//显示所有错误// error_reporting(-1);//屏蔽所有错误error_reporting(0);//不限制php执行时间set_time_limit(0);//引入需要的文件require_once 'Excel/reader.php';require '../pdo_ht_location.php';//取出所有的文件路径$all_files = read_all_dir('../data');$files = $all_files['file'];foreach ($files as $key => $file) {    preg_match('/\d+/', $file, $arr);    $int = 'K' . $arr[0];    //实例化excelReader,不知道怎么优化,如果有更好的方法,请留言    $data = new SpreadsheetExcelReader();    //设置字符集    $data->setOutputEncoding('utf-8');    //读取文件内容    $data->read($file);    //取出表格里面的数据,变成数组    $aa = $data->sheets[0]['cells'];    //去除第一个数据,也就是表头    array_shift($aa);    foreach ($aa as &$v) {        array_push($v, $int);        //转义单双引号,不然数据库会报错        $v[2] = addslashes($v[2]);        //组合sql语句        $sql = "INSERT INTO `lesson_data`(page_no, page_title, data, template_num) VALUES('{$v[1]}','{$v[2]}','{$v[3]}','{$v[4]}') ;";        //执行sql语句        $pdo->exec($sql);        // die($sql);    }}//递归遍历所有目录function read_all_dir($dir) {    $result = array();    $handle = opendir($dir);    if ($handle) {        while (($file = readdir($handle)) !== false) {            if ($file != '.' && $file != '..') {                $cur_path = $dir . DIRECTORY_SEPARATOR . $file;                if (is_dir($cur_path)) {                    $result['dir'][$cur_path] = read_all_dir($cur_path);                } else {                    $result['file'][] = $cur_path;                }            }        }        closedir($handle);    }    return $result;}
原创粉丝点击