Home PHP Framework ThinkPHP ThinkPHP6 data import and export: realize data batch processing

ThinkPHP6 data import and export: realize data batch processing

Aug 26, 2023 pm 08:04 PM
thinkphp data import Data output

ThinkPHP6 data import and export: realize data batch processing

ThinkPHP6 data import and export: realizing batch processing of data

In actual development, we often encounter the need to import and export data in batches, such as importing Excel tables to the database, or export the data in the database to an Excel file. Such operations can improve development efficiency and reduce the workload of manual data entry. This article will introduce how to use the ThinkPHP6 framework to implement batch processing of data, including specific steps and code examples for data import and export.

1. Data import

  1. Preparation work

First, you need to install the PHPExcel library in the project to process Excel files. You can use Composer to install PHPExcel and execute the following command:

composer require phpoffice/phpexcel
Copy after login

After the installation is completed, a vendor directory will be generated, which contains the relevant files of the PHPExcel library.

  1. Import Excel files

In ThinkPHP6, you can use the request() function to obtain files uploaded by users. First, create a method in the controller to handle the import operation:

public function import()
{
    // 获取上传的文件
    $file = request()->file('file');
    
    // 移动到框架应用根目录/uploads/目录下
    $info = $file->validate(['size' => 1048576, 'ext' => 'xls,xlsx'])->move(ROOT_PATH . 'uploads/');

    if ($info) {
        // 获取上传文件的路径
        $filename = $info->getSaveName();
        
        // 处理Excel导入逻辑
        // ...
        
        // 返回成功信息
        return '数据导入成功!';
    } else {
        // 返回错误信息
        return $file->getError();
    }
}
Copy after login

In the above code, the uploaded file is first obtained through the request() function, and the validity is verified. , limits file size to 1MB, and only allows uploading files in .xls and .xlsx formats. Then use the move() method to move the file to the uploads directory of the framework, and save the file name to the $filename variable.

Next, you can use the PHPExcel library in the import logic to read and process the Excel file. The following is a simple example:

public function import()
{
    // ...

    // 创建PHPExcel对象
    $excel = new PHPExcel();

    // 读取Excel文件
    $reader = PHPExcel_IOFactory::createReader('Excel2007');
    $PHPExcel = $reader->load(ROOT_PATH . 'uploads/' . $filename);

    // 获取第一个工作表
    $sheet = $PHPExcel->getSheet(0);

    // 获取总行数
    $totalRow = $sheet->getHighestRow();

    // 遍历每一行数据
    for ($i = 2; $i <= $totalRow; $i++) {
        // 获取单元格数据
        $name = $sheet->getCell('A' . $i)->getValue();
        $age = $sheet->getCell('B' . $i)->getValue();

        // 处理数据插入操作
        // ...
    }

    // ...
}
Copy after login

In the above code, we use the PHPExcel library to create a PHPExcel object and use the createReader() method to read the Excel file. Then use the getSheet() method to get the object of the first worksheet, and use the getHighestRow() method to get the total number of rows.

Next, by traversing the data of each row, use the getCell() method to obtain the value of the specified cell, and insert the data into the database to complete the import operation.

2. Data export

  1. Export database data

First, create a method in the controller to handle the export operation:

public function export()
{
    // 查询数据库数据
    $data = Db::name('user')->select();
    
    // 处理Excel导出逻辑
    // ...
}
Copy after login

In the above code, use the query constructor of ThinkPHP6Db::name('user')->select() to query user data in the database.

  1. Export to Excel file

Next, we use the PHPExcel library to export the data to an Excel file:

public function export()
{
    // ...
    
    // 创建PHPExcel对象
    $excel = new PHPExcel();
    
    // 设置工作表标题
    $excel->getActiveSheet()->setTitle('用户数据');

    // 设置表头
    $excel->getActiveSheet()->setCellValue('A1', 'ID');
    $excel->getActiveSheet()->setCellValue('B1', '姓名');
    $excel->getActiveSheet()->setCellValue('C1', '年龄');

    // 设置数据内容
    $row = 2;
    foreach($data as $item) {
        $excel->getActiveSheet()->setCellValue('A' . $row, $item['id']);
        $excel->getActiveSheet()->setCellValue('B' . $row, $item['name']);
        $excel->getActiveSheet()->setCellValue('C' . $row, $item['age']);
        $row++;
    }

    // 导出Excel文件
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="user_data.xlsx"');
    header('Cache-Control: max-age=0');
    $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
    $writer->save('php://output');
}
Copy after login

In the above code, we created A PHPExcel object and use the setTitle() method to set the title of the worksheet. Then use the setCellValue() method to set the header and data content.

Finally, send the exported Excel file to the browser for download by setting the response header.

Summary

This article introduces how to use the ThinkPHP6 framework to implement batch processing of data, including specific steps and code examples for data import and export. By using the PHPExcel library, we can easily process Excel files, improve development efficiency and reduce the workload of manual data entry. I hope this article is helpful to you and can play a role in actual development.

The above is the detailed content of ThinkPHP6 data import and export: realize data batch processing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

ECharts and Java interface: how to export and share statistical chart data ECharts and Java interface: how to export and share statistical chart data Dec 17, 2023 am 08:44 AM

ECharts is a powerful, flexible and customizable open source chart library that can be used for data visualization and large-screen display. In the era of big data, the data export and sharing functions of statistical charts have become increasingly important. This article will introduce how to implement the statistical chart data export and sharing functions of ECharts through the Java interface, and provide specific code examples. 1. Introduction to ECharts ECharts is a data visualization library based on JavaScript and Canvas open sourced by Baidu, with rich charts.

Complete guide to import data from old phone to new phone (quickly migrate old phone data to new phone for seamless conversion) Complete guide to import data from old phone to new phone (quickly migrate old phone data to new phone for seamless conversion) Feb 02, 2024 pm 06:36 PM

Mobile phones have become an indispensable part of people's lives in modern society. When we buy a new phone, seamlessly transferring important data from the old phone to the new phone is one of the annoying problems. To help you accomplish this task easily, this guide will introduce you to some simple and effective methods. Backing Up Old Phone Data First make sure you have backed up all the data on your old phone before starting any data migration. Computer backup or specialized backup tools can be used to ensure the security of your data through cloud storage services. Synchronize data using cloud storage services such as Apple's iCloud and Android's Google Drive. Many modern smartphones provide cloud storage services. Important data such as photos, memos, etc., log in and

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

One click to get it done! How to quickly import data from old mobile phones to Huawei mobile phones One click to get it done! How to quickly import data from old mobile phones to Huawei mobile phones Mar 22, 2024 pm 09:51 PM

In daily life, we often have the need to replace our mobile phones with new ones. When we buy a new Huawei mobile phone, how to quickly and conveniently import the data from the old phone to the new phone has become a concern for many users. Fortunately, Huawei mobile phones provide a series of convenient methods to help users quickly import old mobile phone data to new mobile phones with one click, allowing us to easily transition to a new mobile phone experience. First of all, we can use the &quot;Quick Transfer&quot; function that comes with Huawei mobile phones to achieve fast data transmission. Open the settings of the new phone and find “Quick

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

See all articles