版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hj960511/article/details/70423049
请先下载phpexcel插件后在使用如下代码运行
phpexcel插件下载地址:http://www.chtml.cn/topic/show/40
实例代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>EXCEL表格转换成json数据工具</title>
</head>
<body>
<?php
/*
* 将excel转换为数组 by aibhsc
* */
ini_set('max_execution_time', '0');
require('PHPExcel.php');//引入PHP EXCEL类
function dump($data){
echo '<pre>';
print_r($data);
echo '</pre>';
}
function format_excel2array($filePath='',$sheet=0){
if(empty($filePath) or !file_exists($filePath)){die('file not exists');}
$PHPReader = new PHPExcel_Reader_Excel2007(); //建立reader对象
if(!$PHPReader->canRead($filePath)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($filePath)){
echo 'no Excel';
return ;
}
}
$PHPExcel = $PHPReader->load($filePath); //建立excel对象
$currentSheet = $PHPExcel->getSheet($sheet); //**读取excel文件中的指定工作表*/
$allColumn = $currentSheet->getHighestColumn(); //**取得最大的列号*/
$allRow = $currentSheet->getHighestRow(); //**取得一共有多少行*/
$data = array();
for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){ //循环读取每个单元格的内容。注意行从1开始,列从A开始
for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
$addr = $colIndex.$rowIndex;
$cell = $currentSheet->getCell($addr)->getValue();
if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
$cell = $cell->__toString();
}
$data[$rowIndex][$colIndex] = $cell;
}
}
return $data;
}
function getUrl($str) {
preg_match("/href=\"(.*)\" /", $str, $a);
return $a[1];
}
function mvtags($str){
$str = implode('|rencongcong,',$str);
$str = strip_tags($str,'<p><br/><br>');
$str = explode('|rencongcong,',$str);
return $str;
}
$arr = format_excel2array('./asp.xls');
$title = implode(',',$arr[1]);
$db = array();
foreach($arr as $k=>$v){
$str = $v;
$v = mvtags($v);
$db[$k]['title'] = $v['0'];
$db[$k]['time'] = $v['1'];
$db[$k]['node_id'] = $v['2'];
$db[$k]['content'] = $v['3'];
$db[$k]['uid'] = $v['4'];
$db[$k]['homepage'] = getUrl($str['F']);
$db[$k]['demo'] = getUrl($str['G']);
$db[$k]['download'] = $v['7'];
}
$db = json_encode($db,true);
file_put_contents('./asp.json',$db,FILE_APPEND);
?>
</body>
</html>