class excel_tool{ const EXCEL_READER_PATH = '/../Vendor/excelReader/reader.php'; // 引入 reader.php 的路径,根据实际情况改 protected static $readerObj; public static $charset = 'utf-8'; // 结果字符集。可以改 /** * read
class excel_tool{
const EXCEL_READER_PATH = '/../Vendor/excelReader/reader.php'; // 引入 reader.php 的路径,根据实际情况改
protected static $readerObj;
public static $charset = 'utf-8'; // 结果字符集。可以改
/**
* reader excel file by path
* @param $filePath string excel file path
* @param @getDataByRow bool 按行对数据分组或全部放在一组
* @param @charset set 输出结果字符集
* @return array result data
*/
public static function readFile($filePath, $getDataByRow = true, $charset = 'utf-8'){
self::$charset = $charset;
$readerObj = self::getReaderInstance();
$readerObj->read($filePath);
$readerObj->setOutputEncoding(self::$charset);
$resultArr = array();
//需要对结果进行excelIconv 处理
if ($getDataByRow === true) {
for ($i = 1; $i <= $readerObj->sheets[0]['numRows']; $i++) {
$arr = array();
for ($j = 1; $j <= $readerObj->sheets[0]['numCols']; $j++) {
$arr[] = self::excelIconv($readerObj->sheets[0]['cells'][$i][$j]);
}
$resultArr[] = $arr;
}
} else {
for ($i = 1; $i <= $readerObj->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $readerObj->sheets[0]['numCols']; $j++) {
$resultArr[] = self::excelIconv($readerObj->sheets[0]['cells'][$i][$j]);
}
}
$resultArr = array_unique($resultArr);
}
return $resultArr;
}
/**
* change the excel input charset
* @param $input string excel input
* @param string iconv input by self::$charset
*/
public static function excelIconv($input){
return iconv('Unicode', self::$charset, $input);
}
/**
* get static reader obj
*/
public static function getReaderInstance(){
if (empty(self::$readerObj)) {
require_once(dirname(__FILE__) . self::EXCEL_READER_PATH);
self::$readerObj = new Spreadsheet_Excel_Reader();
}
return self::$readerObj;
}
}
//使用方法
//传入路径,不传false 默认按行取数据
$xlsdata = excel_tool::readFile('./test.xls');
var_dump($xlsdata);
//结果:test1是在A列第一行,test2是在A列第二行
//array(2) { [0]=> array(1) { [0]=> string(5) "test1" } [1]=> array(1) { [0]=> string(5) "test2" } }
