最近在尝试通过php读取excel以及txt里的数据
php读取excel
用到了PhpOffice\PhpSpreadsheet
读取单元格值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php require_once 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\IReader; use PhpOffice\PhpSpreadsheet\IOFactory; $inputFileName = 'Chinese_Family_Name(1k).xlsx'; /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); // Get the value from cell A1 echo $cellValue = $spreadsheet->getActiveSheet()->getCell('A3')->getValue(); echo '<br>'; |
获取总数据行数
1 2 3 4 |
<?php $worksheet = $spreadsheet->getActiveSheet(); echo $highestRow = $worksheet->getHighestRow(); // e.g. 10 echo '<br>'; |
遍历数据
1 2 3 4 5 6 7 |
<?php for ($i = 1; $i <= $highestRow; $i++) { echo $cellValue = $spreadsheet->getActiveSheet()->getCell("A$i")->getValue(); echo ','; echo $cellValue = $spreadsheet->getActiveSheet()->getCell("B$i")->getValue(); echo '<br>'; } |
php读取txt
用到了两个行数
读取特定行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function get_line( $file_name , $start , $limit ) { $f = new SplFileObject( $file_name,'r'); $f->seek( $start ); //$ret = Array(); $ret = ""; for( $i = 0 ; $i < $limit ; $i++ ) { $str = $f->current(); $ret .= $str; $f->next(); } return $ret; } |
获取总数据行数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function count_line($file){ $fp=fopen($file, "r"); $i=0; while(!feof($fp)) { //每次读取2M if($data=fread($fp,1024*1024*2)){ //计算读取到的行数 $num=substr_count($data,"\n"); $i+=$num; } } fclose($fp); return $i; } |
获取总行数并获取特定行值
1 2 3 4 5 6 7 8 9 10 |
$inputFileName = 'Chinese_Names_Corpus_Gender(120W).txt'; $file = $inputFileName; $lines = count_line($inputFileName); echo "There are $lines lines in $file"; echo '<br>'; for ($i = 0; $i <= 10; $i++) { echo get_line($inputFileName,$i,1); echo '<br>'; } |
There are no comments yet