PHP学习第N天:用PHPExcel将Excel转化为数组输出

        这些文章都是用来记录php学习经历的,会有很多bug和错误,参考需谨慎。

        工作第N天,再过两天就该发工资了,激动一下!

        利用PHPExcel将读取和导出Excel文件非常方便,但是初次使用会有很多各种各样的小问题,我将这两天遇到的问题和解决方法整理了一下,希望能够对大家有所帮助。

        在整理过程中我参考和使用了大量的互联网上的资料和代码。包括但不仅于下面这些,在这里对各位大牛表示感谢。

        PHPExcel下载链接

        http://blog.csdn.net/yanhui_wei/article/details/7930502

        http://www.cnblogs.com/freespider/p/3284828.html

        http://www.cnblogs.com/shubuqi/p/3411079.html

        http://www.cnblogs.com/yuwensong/p/3771787.html 

        前端页面代码:







        Excel2arr:

canRead($filePath)) {
	$PHPReader = new PHPExcel_Reader_Excel5();
	if (!$PHPReader->canRead($filePath)) {
		return $this->error(null, "no file");
	}
}
$PHPExcel = $PHPReader->load($filePath);
$sheetCount = $PHPExcel->getSheetCount();
$sheetNames = $PHPExcel->getSheetNames();
//var_dump($sheetNames);
//die;
/**读取excel文件中有多少个sheet*/
$objExcel = array();
for ($SheetID = 0; $SheetID < $sheetCount; $SheetID++) {
	/**读取excel文件中的工作表*/
	$name = $sheetNames[$SheetID];
	$currentSheet = $PHPExcel->getSheetByName($name);
	$name = iconv("utf-8", "gb2312", $name);
	/**取得最大的列号*/
	$allColumn = $currentSheet->getHighestColumn();
	/**取得一共有多少行*/
	$allRow = $currentSheet->getHighestRow();
	for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
		/**从第A列开始输出*/
		for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
			$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue();
			$val = iconv("utf-8", "gb2312", $val);
			$objExcel[$name][$currentRow - 1][ord($currentColumn) - 65] = $val;
			//编码需要转换成gb2312
			/*
			$val = urlencode($val);
			$objExcel[$name][$currentRow - 1][ord($currentColumn) - 65] = urldecode($val);
			*/
		}
	}
}

unlink($filePath);
/*
* $objExcel = json_encode($objExcel);
* $objExcel = urldecode($objExcel);
* 读取文件中的内容,因为json_encode()的参数必须是utf-8编码。为了保证汉字输出的结果,这里先将数组中的内容用urlencode进行编码,
* 在被json_encode()编码之后,再用urldecode解码。
*/
//return $objExcel;
var_dump($objExcel);
?>



你可能感兴趣的:(PHP)