背景:
近期在做商品的三级分类时发现,需要将 Excel 表格中的数据导入到数据库中进行后期的数据操作,通过度娘的介绍,以及针对此项目功能的设计要求,参考如下:
1. 在自己的项目中,导入Excel 继承类
网上有很多可使用的代码包,此处以 ThinkPHP 框架为参考,保证路径的正确性...
2. 补充,上一步中所调用的公共函数 "format_excel2array()"
/**
* excel表数据转化为数组
* @param string $filePath
* @param int $sheet
* @return array|void
*/
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;
}
3.运行函数
可以在数据库对应的 "third_category" 表中,查看得到的结果
4.三级分类前端设计效果
5.三级分类前端代码 js
附录 JS 代码参考:
6. 附录代码 >>>