Blogger Information
Blog 21
fans 0
comment 0
visits 28427
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
thinkphp3.2.3实现直接导入Excel文件入数据库
a张张张浩的博客
Original
1291 people have browsed it
 <!DOCTYPE html>
 <html>
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
 </head>
 <body>
  <form action="{:U('upload')}" enctype="multipart/form-data" method="post">
<input type="file"name="photo" />
<input type="submit"value="导入数据">
 </body>
 </html>

先写个HTML

接下来随便thinkphp代码

<?php
namespace Home\Controller;
use Think\Controller;
use PHPExcel_IOFactory;
use PHPExcel;
use Behavior;
class IndexController extends Controller {
public function index(){
$this->display();
}
public function upload() {
ini_set('memory_limit','1024M');
if (!empty($_FILES)) {
$config = array(
'exts' => array('xlsx','xls'),
'maxSize' => 3145728000,
'rootPath' =>"./Public/",
'savePath' => 'Uploads/',
'subName' => array('date','Ymd'),
);
$upload = new \Think\Upload($config);
if (!$info = $upload->upload()) {
$this->error($upload->getError());
}
vendor("PHPExcel.PHPExcel");
$file_name=$upload->rootPath.$info['photo']['savepath'].$info['photo']['savename'];
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式
if ($extension == 'xlsx') {
$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel =$objReader->load($file_name, $encode = 'utf-8');
} else if ($extension == 'xls'){
$objReader =\PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel =$objReader->load($file_name, $encode = 'utf-8');
}elseif(strtolower($filetype)=='csv'){  
            $objReader = PHPExcel_IOFactory::createReader('CSV');  
        }  
$sheet =$objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//取得总行数
$highestColumn =$sheet->getHighestColumn(); //取得总列数
D('pro_info')->execute('truncate table pro_info');
for ($i = 2; $i <= $highestRow; $i++) {
//看这里看这里,前面小写的a是表中的字段名,后面的大写A是excel中位置
$data['pId'] =$objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();
$data['pName'] =$objPHPExcel->getActiveSheet()->getCell("B" .$i)->getValue();
$data['pPrice'] =$objPHPExcel->getActiveSheet()->getCell("C" .$i)->getValue();
$data['pCount'] = $objPHPExcel->getActiveSheet()->getCell("D". $i)->getValue();
//看这里看这里,这个位置写数据库中的表名

D('pro_info')->add($data);
}
$this->success('导入成功!');
} else {
$this->error("请选择上传的文件");
}
}
}

1、下载https://github.com/PHPOffice/PHPExcel 

 PHPExcel_1.8.0 并解压


2、在ThinkPHP\Library\Vendor

新建文件夹PHPExcel

ThinkPHP\Library\Vendor\PHPExcel

3、把PHPExcel_1.8.0_doc\Classes中的文件copy到这个目录中

4、配置好数据库

最后根据上面的上传的代码更改就行了

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post