phpExcel读取文件 sss.xlsx(小于Z列)
<?php
include_once('Classes/PHPExcel.php');//引入PHPExcel文件
$excelPath = "./sss.xlsx";//需要读取的Excel文件
$fileType = PHPExcel_IOFactory::identify($excelPath);//文件名自動判斷文件類型
$reader = PHPExcel_IOFactory::createReader($fileType);//設置以Excel5格式(Excel97-2003工作簿)
$PHPExcel = $reader -> load($excelPath);//載入Excel文件
$sheet = $PHPExcel -> getSheet(0);//讀取第一个sheet(包含隐藏sheet)
$highestRow = $sheet -> getHighestRow();//取得總行數
$highestColumn = $sheet -> getHighestColumn();//取得總列數
//遍歷循環得到Excel
//getCalculatedValue()会有对象
//getFormattedValue()获取到的是公式计算后的值
//getValue()获取的是公式本身
for( $row = 2; $row <= $highestRow; $row++ ){//從第2行開始
for( $col = 'A'; $col <=$highestColumn;$col++){//從A列開始 (限制為列數:小于Z列)
$dataset[$row][] = $sheet -> getCell($col.$row) -> getValue();
}
}
?>
当列数大于Z列时,可使用:
echo PHPExcel_Cell::columnIndexFromString('A');//將字母轉為數字 //输出1
echo PHPExcel_Cell::stringFromColumnIndex(0);//将数字转换为字母 //输出A
结果 | PHPExcel | PHPSpreadsheet |
---|---|---|
1 | PHPExcel_Cell::columnIndexFromString(‘A’); | Coordinate::columnIndexFromString(‘A’); |
‘A’ | PHPExcel_Cell::stringFromColumnIndex(0); | Coordinate::stringFromColumnIndex(1); |
phpspreadsheet需 use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
实现代码:
$Highestcol = PHPExcel_Cell::columnIndexFromString($highestColumn);
for( $row = 2; $row <= $highestRow; $row++ ){//從第2行開始
for( $col = 1; $col <=$Highestcol;$col++){//從第1列開始
//方式1
$column = PHPExcel_Cell::stringFromColumnIndex($col-1);
$dataset[$row][] = $sheet -> getCell($column .$row) -> getValue();
//方式2
//$dataset[$row][] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
效果:返回二位数组 。行-列
ExcelReader.php
<?php
require_once 'PHPExcel.php';
class ExcelReader {
/**
* 读取excel
* @param unknown_type $excelPath:excel路径
* @param unknown_type $allColumn:读取的列数
* @param unknown_type $sheet:读取的工作表
*/
public static function reader_excel($excelPath, $allColumn = 0, $sheet = 0) {
$excel_arr = array();
//默认用excel2007读取excel,若格式 不对,则用之前的版本进行读取
$PHPReader = new PHPExcel_Reader_Excel2007();
if(!$PHPReader->canRead($excelPath)) {
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($excelPath)) {
//返回空的数组
return $excel_arr;
}
}
//载入excel文件
$PHPExcel = new PHPExcel();
$PHPExcel = $PHPReader->load($excelPath);
//获取工作表总数
$sheetCount = $PHPExcel->getSheetCount();
//判断是否超过工作表总数,取最小值
$sheet = $sheet < $sheetCount ? $sheet : $sheetCount;
//默认读取excel文件中的第一个工作表
$currentSheet = $PHPExcel->getSheet($sheet);
if(empty($allColumn)) {
//取得最大列号,这里输出的是大写的英文字母,ord()函数将字符转为十进制,65代表A
$allColumn = ord($currentSheet->getHighestColumn()) - 65 + 1;
}
//取得一共多少行
$allRow = $currentSheet->getHighestRow();
//从第二行开始输出,因为excel表中第一行为列名
for($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
for($currentColumn = 0; $currentColumn <= 5; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$excel_arr[$currentRow - 2][$currentColumn] = $val;
}
}
//返回二维数组
return $excel_arr;
}
}
?>