Home PHP Framework ThinkPHP How to use ThinkPHP6 to import and export Excel?

How to use ThinkPHP6 to import and export Excel?

Jun 12, 2023 am 09:23 AM
thinkphp excel import Export

With the development of the Internet, there are increasing demands for data import and export, especially in enterprises. As a very popular office software, Excel is also widely used for data storage and processing. Therefore, how to use ThinkPHP6 to import and export Excel has become a very important issue. This article will introduce the steps for Excel import and export using ThinkPHP6.

1. Excel export

ThinkPHP6 provides a very convenient Excel export tool class - PHPExcel. You can use PHPExcel to export data into Excel files. The specific steps are as follows:

1. Install the PHPExcel class library

Add the PHPExcel class library in the composer.json file:

"require": {
    "phpoffice/phpexcel": "^1.8"
},
Copy after login

Execute the command to install the PHPExcel class library:

composer install
Copy after login

2. Create an Excel export Controller

Create a controller class to handle Excel export requests:

namespace appdmincontroller;

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx as Writer;

class Excel extends Base
{
    public function export()
    {
        // TODO: 导出Excel
    }
}
Copy after login

3. Construct the data source

Before exporting Excel, you need to prepare the data to be exported source. There are usually two ways to obtain data sources:

(1) Get data from the database

namespace appdmincontroller;

use appdminmodelUser as UserModel;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx as Writer;

class Excel extends Base
{
    public function export()
    {
        $users = UserModel::select()->toArray();

        $spreadsheet = new Spreadsheet();

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '姓名');
        $sheet->setCellValue('C1', '性别');
        $sheet->setCellValue('D1', '年龄');

        $row = 2;
        foreach ($users as $user) {
            $sheet->setCellValue('A' . $row, $user['id']);
            $sheet->setCellValue('B' . $row, $user['name']);
            $sheet->setCellValue('C' . $row, $user['gender']);
            $sheet->setCellValue('D' . $row, $user['age']);
            $row++;
        }

        $writer = new Writer($spreadsheet);
        $writer->save('users.xlsx');
    }
}
Copy after login

(2) Get data from other data sources

If we want to Some data are exported to Excel files, but these data are not stored in the database. For example, we want to export some order information in the form of Excel, etc. At this time, we can obtain this data through other methods, such as obtaining it from the network API interface.

namespace appdmincontroller;

use GuzzleHttpClient;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx as Writer;

class Excel extends Base
{
    public function export()
    {
        $client = new Client();

        $response = $client->get('https://api.example.com/orders');

        $orders = json_decode($response->getBody()->getContents(), true);

        $spreadsheet = new Spreadsheet();

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', '订单编号');
        $sheet->setCellValue('B1', '下单人');
        $sheet->setCellValue('C1', '订单金额');

        $row = 2;
        foreach ($orders as $order) {
            $sheet->setCellValue('A' . $row, $order['id']);
            $sheet->setCellValue('B' . $row, $order['user']);
            $sheet->setCellValue('C' . $row, $order['amount']);
            $row++;
        }

        $writer = new Writer($spreadsheet);
        $writer->save('orders.xlsx');
    }
}
Copy after login

2. Excel import

It is also very convenient to use ThinkPHP6 to process Excel import. It is also implemented using the PHPExcel class library. The specific steps are as follows:

1. Install the PHPExcel class library

Same as the steps for Excel export, you need to install the PHPExcel class library first.

2. Create Excel Import Controller

Create a controller class to handle Excel import requests:

namespace appdmincontroller;

use PhpOfficePhpSpreadsheetIOFactory;

class Excel extends Base
{
    public function import()
    {
        $file = request()->file('file');

        $info = $file->validate(['ext' => 'xlsx'])->move('uploads');

        if ($info) {
            $filename = 'uploads/' . $info->getSaveName();

            $reader = IOFactory::createReader('Xlsx');
            $spreadsheet = $reader->load($filename);

            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();

            $data = [];

            for ($row = 2; $row <= $highestRow; $row++) {
                $rowData = [];
                for ($column = 'A'; $column <= $highestColumn; $column++) {
                    $cellValue = $sheet->getCell($column . $row)->getValue();
                    $rowData[] = $cellValue;
                }
                $data[] = $rowData;
            }

            unlink($filename);

            dump($data);
        } else {
            echo $file->getError();
        }
    }
}
Copy after login

3. Upload Excel file

We need Add an upload form to the view to allow users to upload Excel files to be imported.

<form method="post" action="admin/excel/import"
      enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="上传">
</form>
Copy after login

4. Processing imported data

After importing Excel, we can obtain the imported data through the API provided by PHPExcel. In the above code, we use the following code to obtain data:

$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

$data = [];

for ($row = 2; $row <= $highestRow; $row++) {
    $rowData = [];
    for ($column = 'A'; $column <= $highestColumn; $column++) {
        $cellValue = $sheet->getCell($column . $row)->getValue();
        $rowData[] = $cellValue;
    }
    $data[] = $rowData;
}
Copy after login

The imported data is stored in the $data variable. We can perform subsequent data processing operations, such as inserting data into the database.

In summary, using ThinkPHP6 to import and export Excel is relatively simple. By using the PHPExcel class library, we can easily read and export Excel files.

The above is the detailed content of How to use ThinkPHP6 to import and export Excel?. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How to get Douyin private message emoticons on WeChat? How to export the private message emoticon package? How to get Douyin private message emoticons on WeChat? How to export the private message emoticon package? Mar 21, 2024 pm 10:01 PM

With the continuous rise of social media, Douyin, as a popular short video platform, has attracted a large number of users. On Douyin, users can not only show their lives but also interact with other users. In this interaction, emoticons have gradually become an important way for users to express their emotions. 1. How to get Douyin private message emoticons on WeChat? First of all, to get private message emoticons on the Douyin platform, you need to log in to your Douyin account, then browse and select the emoticons you like. You can choose to send them to friends or collect them yourself. After receiving the emoticon package on Douyin, you can long press the emoticon package through the private message interface, and then select the &quot;Add to Emoticon&quot; function. In this way, you can add this emoticon package to Douyin’s emoticon library. 3. Next, we need to add the words in the Douyin emoticon library

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.

Exporting songs downloaded from QQ Music as mp3 on mac only requires two steps Exporting songs downloaded from QQ Music as mp3 on mac only requires two steps Jan 05, 2024 pm 07:10 PM

Listening to music is a very common thing, I believe many friends will do it no matter where they are. What software do you usually use to listen to music? Do you use QQ Music like me? I currently use QQ Music to listen to songs, and it can be used not only on mobile phones, but also on Mac computers. In addition to listening to songs online, we can also download our favorite songs from QQ Music to the computer. However, the songs downloaded from QQ Music for Mac are not in the format we need. What we need is music in MP3 format. So how to export the songs downloaded from QQ Music for Mac to MP3 format? How to export and convert songs downloaded from QQ Music for Mac to MP3 format? If you want to export and convert songs downloaded from QQ Music for Mac to MP

How to export xmind files to pdf files How to export xmind files to pdf files Mar 20, 2024 am 10:30 AM

xmind is a very practical mind mapping software. It is a map form made using people's thinking and inspiration. After we create the xmind file, we usually convert it into a pdf file format to facilitate everyone's dissemination and use. Then How to export xmind files to pdf files? Below are the specific steps for your reference. 1. First, let’s demonstrate how to export the mind map to a PDF document. Select the [File]-[Export] function button. 2. Select [PDF document] in the newly appeared interface and click the [Next] button. 3. Select settings in the export interface: paper size, orientation, resolution and document storage location. After completing the settings, click the [Finish] button. 4. If you click the [Finish] button

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.

How to export the cross-section diagram in Kujiale_How to export the cross-section diagram in Kujiale How to export the cross-section diagram in Kujiale_How to export the cross-section diagram in Kujiale Apr 02, 2024 pm 06:01 PM

1. First, open the design plan to be processed in Kujiale and click on the construction drawings under the drawing list above. 2. Then click to select the full-color floor plan. 3. Then hide the unnecessary furniture in the drawing, leaving only the furniture that needs to be exported. 4. Finally, click Download.

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.

See all articles