php获取excel表格内容,利用PHPExcel如何读取表格中内容
利用PHPExcel如何讀取表格的內(nèi)容呢?話不多說,下面的這篇文章將給大家詳細(xì)的介紹關(guān)于PHPExcel讀取表格中內(nèi)容的方法。
先引入類IOFactory.phprequire_once '../PHPExcel/IOFactory.php';
$filePath = "test.xlsx"; // 測(cè)試文件
加載測(cè)試文件$inputFileType = PHPExcel_IOFactory::identify($filePath) 判斷文件類型
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 實(shí)例化類型對(duì)象
$objPHPExcel = $objReader->load($filePath); 加載文件
下面主要判斷Excel2007和Excel5類型,即xlsx/xlsm/xltx/xltm和xls/xlt格式文件try {
$inputFileType = PHPExcel_IOFactory::identify($filePath);
if ($inputFileType !== "Excel5" && $inputFileType !== "Excel2007" ) {
unlink($filePath) && str_alert(-1,"請(qǐng)確保導(dǎo)入的文件格式正確!");
}
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($filePath);
} catch(Exception $e) {
unlink($filePath) && str_alert(-1,'加載文件發(fā)生錯(cuò)誤:”'.pathinfo($filePath,PATHINFO_BASENAME).'”: '.$e->getMessage());
}
獲取當(dāng)前工作表$sheet = $objPHPExcel->getSheet(0);
//或者
$sheet = $objPHPExcel->getActiveSheet();
獲取工作表行數(shù)和列數(shù)$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
注意:有時(shí)候你會(huì)發(fā)現(xiàn)你的表格明明有內(nèi)容的行數(shù)就5行,但是獲取到的$highestRow卻有7,8行或者更多,這可能是因?yàn)槟阍诓僮髂愕谋砀竦臅r(shí)候不小心點(diǎn)擊了其它行數(shù),雖然沒有填寫內(nèi)容,但getHighestRow也是能夠識(shí)別出行數(shù);
想要獲取有內(nèi)容的行數(shù)應(yīng)該使用getHighestDataRow和getHighestDataColumn
源碼注釋是這樣介紹的string Highest row number that contains data,即包含數(shù)據(jù)的字符串最高行數(shù).
單元格具體內(nèi)容
xlsx類型的表格單元格是通過類似xy軸坐標(biāo)來獲取的,
可通過類似$sheet->getCell("A1")->getValue();
$sheet->getCell("B2")->getValue();
獲取相應(yīng)位置的內(nèi)容,
如果不想通過字母了來遍歷獲取,可以用數(shù)字索引方法$sheet->getCellByColumnAndRow(0,1);
$sheet->getCellByColumnAndRow(1,2);
注意坐標(biāo)中第一個(gè)參數(shù)從0開始,0代表A,1代表B...,第二個(gè)參數(shù)從1開始.
下面是遍歷表格獲取全部單元格內(nèi)容:$dataSet=array();
for ($column = "A"; $column <= $highestColumn; $column++) {//列數(shù)是以A列開始
for ($row = 4; $row <= $highestRow; $row++) { //行數(shù)是以第4行開始
$cell = $sheet->getCell($column . $row)->getValue();
if($cell instanceof PHPExcel_RichText) { //富文本轉(zhuǎn)換字符串
$cell = $cell->__toString();
}
$dataSet[$row][] = $cell;
}
}
其中富文本轉(zhuǎn)換字符串,是使用$cell instanceof PHPExcel_RichText判斷是否為富文本,查閱資料發(fā)現(xiàn)如果你的單元格中字符串包含兩種以上的字體會(huì)自動(dòng)被設(shè)為富文本,這時(shí)候需要__toString()轉(zhuǎn)換
判斷合并單元格是否位于最左上角
當(dāng)我們循環(huán)輸出所有單元格后發(fā)現(xiàn),一些被合并的單元格只有最左上坐標(biāo)的是有內(nèi)容的,其他都是null
例如A4,A5合并成一個(gè)單元格,getCell("A4")是有正常內(nèi)容的,但是getCell("A5")是null.
isMergeRangeValueCell可以用來判斷某個(gè)具體的單元格是否為最左上角$sheet->getCell('A' . $row)->isMergeRangeValueCell()
當(dāng)$row為4的時(shí)候是返回true,5的時(shí)候返回false
轉(zhuǎn)換時(shí)間
獲取表格中時(shí)間格式的內(nèi)容,需要PHPExcel_Shared_Date::ExcelToPHP()來轉(zhuǎn)換為php可識(shí)別的時(shí)間格式date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sometime);
相關(guān)推薦:
總結(jié)
以上是生活随笔為你收集整理的php获取excel表格内容,利用PHPExcel如何读取表格中内容的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java对象的初始化顺序_JAVA 对象
- 下一篇: 动态规划算法php,php算法学习之动态