05月20, 2015

PHPExcel读取xls文件

        $filepath = './1/1.xls';
        // 导入PHPExcel
        import("Common.Libs.PHPExcel","",".php");

        // 为了可以读取所有版本的xls
        $objReader = \PHPExcel_IOFactory::createReader("Excel2007");
        if (!$objReader->canRead($filepath)) {
            $objReader = \PHPExcel_IOFactory::createReader("Excel5");
            if (!$objReader->canRead($filepath)) {
                echo "选取文件格式不正确";
                return;
            }
        }

        // 设置只读
        $objReader->setReadDataOnly(true);

        // 获取所有的工作表名字
        $sheetNames = $objReader->listWorksheetNames($filepath);

        // 读取文件
        $objPHPExcel = $objReader->load($filepath);
        $objWorksheet = $objPHPExcel->getSheet(0);

        // 获取一共多少个工作表
        $sheetCount = $objPHPExcel->getSheetCount();

        // 一共多少行
        $highestRow = $objWorksheet->getHighestRow();
        // 一共多少列
        $highestColumn = $objWorksheet->getHighestColumn();
        // 字幕列标识转换成数字
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);

        // 初始化结果数组
        $excelData = array();
        // 循环读取数据
        for ($row=1; $row <= $highestRow; $row++) { 
            for ($col=1; $col <= $highestColumnIndex; $col++) { 
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
            }
        }

        // 打印结果数组
        p($excelData);


例外一种:

canRead($filePath))
{                       
    $PHPReader = new PHPExcel_Reader_Excel5();   
    if(!$PHPReader->canRead($filePath))
    {                       
        echo '未发现Excel文件!';
        return;
    }
}
  
//不需要读取整个Excel文件而获取所有工作表数组的函数,感觉这个函数很有用,找了半天才找到
$sheetNames  = $PHPReader->listWorksheetNames($filePath);
  
//读取Excel文件
$PHPExcel = $PHPReader->load($filePath);
  
//获取工作表的数目
$sheetCount = $PHPExcel->getSheetCount();
  
//选择第一个工作表
$currentSheet = $PHPExcel->getSheet(0);
  
//取得一共有多少列
$allColumn = $currentSheet->getHighestColumn();   
  
//取得一共有多少行
$allRow = $currentSheet->getHighestRow();  
  
//循环读取数据,默认编码是utf8,这里转换成gbk输出
for($currentRow = 1;$currentRow<=$allRow;$currentRow++)
{
    for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++)
    {
        $address = $currentColumn.$currentRow;
        echo iconv( 'utf-8','gbk', $currentSheet->getCell($address)->getValue() )."\t";
    }
    echo "";
}
?>


本文链接:https://lxyit.com/article/show/72.html

-- EOF --