How to use PHP and UniApp to import and export data in Excel

WBOY
Release: 2023-07-04 17:54:01
Original
2584 people have browsed it

How to use PHP and UniApp to implement Excel import and export of data

Importing and exporting data is a requirement we often encounter in web development. As one of the commonly used data formats, Excel can clearly display data in tabular form and has high compatibility, making it the choice of many people. This article will introduce how to use PHP and UniApp to import and export data in Excel respectively.

First, let’s look at how to import data into Excel through PHP.

  1. Install PHPExcel library
    PHPExcel is a powerful and easy-to-use PHP library for processing Excel files. We first need to install the PHPExcel library in the project.

Can be installed through Composer, add the following code to the composer.json file:

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

Then execute composer install in the command line to complete the installation .

  1. Create an import interface
    In the PHP project, create an Excel import interface to receive the Excel file passed by the front end, parse the file content, store the data in the database or perform other operations.
<?php
require 'vendor/autoload.php';
use PhpOfficePhpSpreadsheetIOFactory;

if ($_FILES['file']['error'] == 0) {
    $file = $_FILES['file']['tmp_name'];
    $reader = IOFactory::createReader('Xlsx');
    $spreadsheet = $reader->load($file);
    $worksheet = $spreadsheet->getActiveSheet();
    
    // 获取数据并处理
    $data = [];
    foreach ($worksheet->getRowIterator() as $row) {
        $rowData = [];
        foreach ($row->getCellIterator() as $cell) {
            $rowData[] = $cell->getValue();
        }
        $data[] = $rowData;
    }
    
    // 处理数据
    // ...
    
    // 返回处理结果
    echo json_encode([
        'status' => 1,
        'message' => '上传成功'
    ]);
} else {
    echo json_encode([
        'status' => 0,
        'message' => '上传失败'
    ]);
}
?>
Copy after login
  1. Calling the interface in UniApp
    In the UniApp project, use uni.request to call the above interface and upload the Excel file to the server as FormData.
export default {
    methods: {
        importExcel() {
            uni.chooseMessageFile({
                count: 1,
                success: (res) => {
                    const tempFilePath = res.tempFiles[0].path;
                    uni.uploadFile({
                        url: 'http://localhost/import.php',
                        filePath: tempFilePath,
                        name: 'file',
                        success: (res) => {
                            const data = JSON.parse(res.data);
                            if (data.status === 1) {
                                uni.showToast({
                                    title: '导入成功',
                                    icon: 'success'
                                });
                            } else {
                                uni.showToast({
                                    title: '导入失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: () => {
                            uni.showToast({
                                title: '上传失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            });
        }
    }
}
Copy after login

Let’s look at how to export data to Excel through UniApp.

  1. Create export interface
    In the PHP project, create an Excel export interface, obtain data from the database as needed, and then export the data as an Excel file for users to download.
<?php
require 'vendor/autoload.php';
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

// 获取数据
$data = [
    ['name', 'age', 'gender'],
    ['Tom', 20, 'Male'],
    ['Lisa', 25, 'Female'],
    // ...
];

// 创建Excel文件
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->fromArray($data);

// 下载文件
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="export.xlsx"');
$writer->save('php://output');
?>
Copy after login
  1. Calling the interface in UniApp
    In the UniApp project, use uni.downloadFile to download the exported Excel file.
export default {
    methods: {
        exportExcel() {
            uni.downloadFile({
                url: 'http://localhost/export.php',
                success: (res) => {
                    uni.saveFile({
                        tempFilePath: res.tempFilePath,
                        success: (res) => {
                            uni.showToast({
                                title: '导出成功',
                                icon: 'success'
                            });
                        }
                    });
                },
                fail: () => {
                    uni.showToast({
                        title: '导出失败',
                        icon: 'none'
                    });
                }
            });
        }
    }
}
Copy after login

Through the above steps, we can easily implement the Excel import and export functions of data. Whether on the PHP backend or the UniApp frontend, this task can be accomplished through relevant libraries and interfaces. Hope this article can be helpful to you!

The above is the detailed content of How to use PHP and UniApp to import and export data in Excel. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!