composer require phpoffice/phpexcel
//导入Excel
function data_import($filename, $exts = 'xls')
{
ini_set('memory_limit', '-1');//取消内存限制
set_time_limit(0);//无时间限制可以一直执行到结束
//创建PHPExcel对象,注意,不能少了\
new \PHPExcel();
//如果excel文件后缀名为.xls,导入这个类
if ($exts == 'xls') {
import("Org.Util.PHPExcel.Reader.Excel5");
$PHPReader = new \PHPExcel_Reader_Excel5();
} else if ($exts == 'xlsx') {
import("Org.Util.PHPExcel.Reader.Excel2007");
$PHPReader = new \PHPExcel_Reader_Excel2007();
} else if ($exts == 'csv') {
import("Org.Util.PHPExcel.Reader.CSV");
$PHPReader = new \PHPExcel_Reader_CSV();
} else {
return '不支持的文件类型';
exit();
}
//载入文件
$PHPExcel = $PHPReader->load($filename, $encode = 'utf-8');
//获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
$currentSheet = $PHPExcel->getSheet(0);
//获取总列数
$allColumn = $currentSheet->getHighestColumn();
//获取总行数
$allRow = $currentSheet->getHighestRow();
//循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
if ($allRow > 10000) {
return '文件不能大于10000条';
exit();
}
$i = 0;
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
//从哪列开始,A表示第一列
if (strlen($allColumn) >= 2) {
for ($currentColumn = 'A'; $currentColumn <= 'Z'; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
if ($currentColumn == '') {//指定H列为时间所在列
$data[$i][$currentColumn] = gmdate("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
} else {
//读取到的数据,保存到数组$arr中
$data[$i][$currentColumn] = $currentSheet->getCell($address)->getValue();
// 开始格式化
// 获取excel C2的文本
import("Org.Util.PHPExcel"); // 这里不能漏掉
import("Org.Util.PHPExcel.IOFactory");
$cell = $currentSheet->getCell($address)->getValue();
// 开始格式化
if (is_object($cell)) {
$cell = $cell->__toString();
}
$data[$i][$currentColumn] = $cell;
}
}
$i++;
} else {
for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
if ($currentColumn == '') {//指定H列为时间所在列
$data[$i][$currentColumn] = gmdate("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
} else {
//读取到的数据,保存到数组$arr中
$data[$i][$currentColumn] = $currentSheet->getCell($address)->getValue();
// 开始格式化
// 获取excel C2的文本
import("Org.Util.PHPExcel"); // 这里不能漏掉
import("Org.Util.PHPExcel.IOFactory");
$cell = $currentSheet->getCell($address)->getValue();
// 开始格式化
if (is_object($cell)) {
$cell = $cell->__toString();
}
$data[$i][$currentColumn] = $cell;
}
}
$i++;
}
}
return $data;
}
//导出Excel
function exportExcel($expTitle, $expCellName, $expTableData, $setTitle)
{
ini_set('memory_limit', '-1');//取消内存限制
set_time_limit(0);//无时间限制可以一直执行到结束
$xlsTitle = iconv('utf-8', 'gbk', $expTitle);//文件名称
$fileName = $xlsTitle;//or $xlsTitle 文件名称可根据自己情况设定
$cellNum = count($expCellName);
$dataNum = count($expTableData);
$objPHPExcel = new \PHPExcel();
//设置工作表格名称
$objPHPExcel->getActiveSheet()->setTitle($setTitle);
$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
for ($i = 0; $i < $cellNum; $i++) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
}
// Miscellaneous glyphs, UTF-8
for ($i = 0; $i < $dataNum; $i++) {
for ($j = 0; $j < $cellNum; $j++) {
$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
}
}
// MIME 协议,文件的类型,不设置,会默认html
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// MIME 协议的扩展
header('Content-Disposition:attachment;filename="'.$fileName.'.xlsx"');
// 缓存控制
header('Cache-Control:max-age=0');
$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
// php://output 它是一个只写数据流, 允许你以 print 和 echo一样的方式写入到输出缓冲区。
$writer->save('php://output');
exit;
}
<?php
namespace app\index\controller;
use app\common\Base;
use think\Db;
use think\Request;
use PHPExcel;//导入PHPExcel
use PHPExcel_IOFactory;//导入PHPExcel__IOFactory
class Demo extends Base
{
//使用phpExcel导入excel文件第一种方法
public function upExcelsOne()
{
$file = $_FILES['file'];
if ($file['error'] > 0) {
return json(['请选择导入文件~']);
exit;
}
$upload_dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . date('Ymd');
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$upload_path = $upload_dir . DS . iconv('UTF-8', 'GBK', $file['name']);
if (move_uploaded_file($file['tmp_name'], $upload_path)) {
$exts = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$data = data_import($upload_path, $exts);
if ($data) {
foreach ($data as $v) {
$arr[] = [
'id' => $v['A'],
'name' => $v['B'],
'sex' => $v['C'],
'tel' => $v['D'],
];
}
//将表格数据存入数据库
$chunk_result = array_chunk($arr, 2000);
// dump($chunk_result);die;
foreach ($chunk_result as $v) {
//此处批量插入数据操作
$res = Db::table('hebei')->insertAll($v);
}
if ($res > 0) {
return json(['status' => true, 'msg' => '导入成功']);
} else {
return json(['status' => false, 'msg' => '导入失败,请重试~']);
}
} else {
return json(['status' => false, 'msg' => '导入失败,请检查表格数据是否存在']);
}
} else {
return json(['status' => false, 'msg' => '导入错误']);
}
}
//使用phpExcel导入excel文件第二种方法
public function upExcelsTwo(Request $request)
{
//获取导入的文件信息
$file = $request->file('file');
if ($file) {
//将Excel上传到指定目录
$info = $file
->validate(['ext' => 'xls,xlsx,csv'])
->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . date('Ymd'), '');
if ($info) {
//获取文件路径
$upload_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . date('Ymd') . DS . $info->getSaveName();
//获取文件名后缀
$exts = $info->getExtension();
//获取Excel表格数据
$data = data_import($upload_path, $exts);
if ($data) {
//遍历获取到的多维数组
foreach ($data as $v) {
//处理数据
$arr[] = [
'id' => $v['A'],
'name' => $v['B'],
'sex' => $v['C'],
'tel' => $v['D'],
];
}
$chunk_result = array_chunk($arr, 2000);
foreach ($chunk_result as $v) {
//此处批量插入数据操作
$res = Db::table('hebei')->insertAll($v);
}
if ($res > 0) {
return json(['status' => true, 'msg' => '导入成功']);
} else {
return json(['status' => false, 'msg' => '导入失败,请重试~']);
}
} else {
return json(['status' => false, 'msg' => '导入失败,请检查表格数据是否存在']);
}
} else {
return json(['status' => false, 'msg' => '导入失败,请重试~']);
}
} else {
return json(['status' => false, 'msg' => '请选择导入文件']);
}
}
//使用phpExcel导出Excel
public function export()
{
//Excle文件名
$xlsName = date('Ymd',time()).rand();
//标题
$xlsCell = array(
array('id', '序号'),
array('name', '用户名'),
array('sex', '性别'),
array('tel', '电话')
);
//查询数据
$xlsData = Db::table('excel')->select();
//Excel工作表名
$setTitle = 'sheet1';
exportExcel($xlsName,$xlsCell,$xlsData,$setTitle);
}
}