在 ThinkPHP 6.0 中實現 excel 導入導出功能,需要使用第三方庫或擴展,例如 phpspreadsheet。
安裝
項目目錄下打開命令行,執行命令:
composer require phpoffice/phpspreadsheet
安裝過程
$ composer require phpoffice/phpspreadsheet
Using version ^1.25 for phpoffice/phpspreadsheet
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 8 installs, 0 updates, 0 removals
- Installing psr/http-factory (1.0.1): Loading from cache
- Installing psr/http-client (1.0.1): Loading from cache
- Installing markbaker/matrix (3.0.1): Downloading (100%)
- Installing markbaker/complex (3.0.2): Downloading (100%)
- Installing myclabs/php-enum (1.8.4): Downloading (100%)
- Installing maennchen/zipstream-php (2.1.0): Downloading (100%)
- Installing ezyang/htmlpurifier (v4.16.0): Downloading (100%)
- Installing phpoffice/phpspreadsheet (1.25.2): Downloading (100%)
ezyang/htmlpurifier suggests installing cerdic/css-tidy (If you want to use the filter 'Filter.ExtractStyleBlocks'.)
ezyang/htmlpurifier suggests installing ext-tidy (Used for pretty-printing HTML)
phpoffice/phpspreadsheet suggests installing ext-intl (PHP Internationalization Functions)
phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing dompdf/dompdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing mitoteam/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers)
Writing lock file
Generating autoload files
> @php think service:discover
Succeed!
> @php think vendor:publish
File D:\tp_solve\config\trace.php exist!
Succeed!
加載類庫
use PhpOffice\PhpSpreadsheet\IOFactory;
添加路由
上傳文件改用post提交
Route::post('productImport', 'ProductOrder/importExcel');
實戰代碼
/**
* excel 導入
* @return false|string
*/
public function importExcel()
{
$file = request()->file('file');
if (!$file) {
print_r('請選擇需要導入的文件');die;
}
// 加載文件
$spreadsheet = IOFactory::load($file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
// 處理文件數據
$data = [];
foreach ($sheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
// 不讀取第一行 標題
if ($rowIndex == 1) {
continue;
}
$cellIterator = $row->getCellIterator();
$row = [];
foreach ($cellIterator as $cell) {
$row[] = $cell->getValue();
}
$data[] = $row;
}
// 數據入庫處理
print_r($data);die;
}
tp6實現Excel導入很簡單,實現步驟如下:
1、使用composer安裝PHPExcel
composer require phpoffice/phpexcel
image.png
2、執行composer更新
composer update
3、代碼實現
<?php
declare (strict_types = 1);
namespace app\union\controller;
use app\Request;
use app\union\model\Groups;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;
use PHPExcel_IOFactory; //通過composer加載的第三方類,直接在頭部引入一下就可以
class Group extends Base
{
public function import_save(Request $request){
if(!$request->param('excel')){
return returnJson('500','請上傳excel文件');
}
$path = public_path().$request->param('excel');
//實例化PHPExcel類
$PHPExcel = new \PHPExcel();
//默認用excel2007讀取excel,若格式不對,則用之前的版本進行讀取
$PHPReader = new \PHPExcel_Reader_Excel2007();
if (!$PHPReader->canRead($path)) {
$PHPReader = new \PHPExcel_Reader_Excel5();
if (!$PHPReader->canRead($path)) {
return returnJson('500','請上傳excel文件');
}
}
//讀取Excel文件
$PHPExcel = $PHPReader->load($path);
//讀取excel文件中的第一個工作表
$sheet = $PHPExcel->getSheet(0);
//取得最大的列號
$allColumn = $sheet->getHighestColumn();
//取得最大的行號
$allRow = $sheet->getHighestRow();
//從第二行開始插入,第一行是列名
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
//獲取B列的值
$data = [
'number'=>$PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue(),
'nickName'=>$PHPExcel->getActiveSheet()->getCell("B" . $currentRow)->getValue(),
'name'=>$PHPExcel->getActiveSheet()->getCell("C" . $currentRow)->getValue(),
'tel'=>$PHPExcel->getActiveSheet()->getCell("D" . $currentRow)->getValue(),
'money'=>$PHPExcel->getActiveSheet()->getCell("E" . $currentRow)->getValue(),
'time'=>self::get_date_by_excel($PHPExcel->getActiveSheet()->getCell("F" . $currentRow)->getValue()),
'is_pay'=>$PHPExcel->getActiveSheet()->getCell("G" . $currentRow)->getValue(),
'shop_name'=>$PHPExcel->getActiveSheet()->getCell("H" . $currentRow)->getValue(),
'remarks'=>$PHPExcel->getActiveSheet()->getCell("I" . $currentRow)->getValue(),
'status'=>0,
'created_at'=>date('Y-m-d')
];
if($data['number'] == ''){
$result = 1;
continue;
}else{
$find = Groups::where(array('number'=>$data['number']))->find();
if($find){
$result = 1;
continue;
}else{
$result=Db::name('group')->insert($data);
}
}
}
if($result){
return returnJson('200','導入成功');
}else{
return returnJson('500','導入失敗');
}
}
public static function get_date_by_excel($date){
if (!$date || $date == '0000-00-00') return null;
$unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date);
return gmdate('Y-m-d H:i',$unix_time);
}
}
?>
ps: