1、先在github里面下载PHPexcel这个类库
https://github.com/PHPOffice/PHPExcel
2、解压之后把它复制到extend里面
控制器代码如下:
<?php
/**
* Created by PhpStorm.
* User: luxiao
* Date: 2017/5/8
* Time: 16:49
*/
namespace appindexcontroller;
use thinkLoader;
use thinkController;
class Excel extends Controller
{
function excel()
{
$path = dirname(__FILE__); //找到当前脚本所在路径
Loader::import('PHPExcel.Classes.PHPExcel'); //手动引入PHPExcel.php
Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory'); //引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
$PHPExcel = new PHPExcel(); //实例化
$PHPSheet = $PHPExcel->getActiveSheet();
$PHPSheet->setTitle("demo"); //给当前活动sheet设置名称
$PHPSheet->setCellValue("A1","姓名")->setCellValue("B1","分数");//表格数据
$PHPSheet->setCellValue("A2","张三")->setCellValue("B2","2121");//表格数据
$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007"); //创建生成的格式
header('Content-Disposition: attachment;filename="表单数据.xlsx"'); //下载下来的表格名
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
}
}
|
调用excel方法就可以生成一个表格了,后续的根据自己的需要自己去写代码.
PHPexcel 表格数据导入数据库 city 表,在这之前自己先创建好表单,我这次用的都是地址数据表做的测试:
function inserExcel()
{
Loader::import('PHPExcel.Classes.PHPExcel');
Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
//获取表单上传文件
$file = request()->file('excel');
$info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads'); //上传验证后缀名,以及上传之后移动的地址
if ($info) {
// echo $info->getFilename();
$exclePath = $info->getSaveName(); //获取文件名
$file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath; //上传文件的地址
$objReader =PHPExcel_IOFactory::createReader('Excel2007');
$obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8'); //加载文件内容,编码utf-8
echo "<pre>";
$excel_array=$obj_PHPExcel->getsheet(0)->toArray(); //转换为数组格式
array_shift($excel_array); //删除第一个数组(标题);
$city = [];
foreach($excel_array as $k=>$v) {
$city[$k]['Id'] = $v[0];
$city[$k]['code'] = $v[1];
$city[$k]['path'] = $v[2];
$city[$k]['pcode'] = $v[3];
$city[$k]['name'] = $v[4];
}
Db::name('city')->insertAll($city); //批量插入数据
} else {
echo $file->getError();
}
|
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost/chexian5.0/index.php/index/excel/intoexcel" enctype="multipart/form-data" method="post">
<input type="file" name="excel" />
<input type="submit" value="导入">
</form>
</body>
</html>
|
(责任编辑:yang) |