Bootstrap

NextJs - ServerAction获取文件并处理Excel

NextJs - ServerAction获取文件并处理Excel

一. 客户端

'use client';
import { uploadExcel } from '@actions/batchInquirySystem/api';
import type { UploadProps } from 'antd';
import { Upload } from 'antd';

/**
 * 创建问询内容
 */
const Page = () => {
    const customRequest = async (option: any) => {
        const file = option.file as File;
        const formData = new FormData();
        formData.append('file', file);
        const response: any = await uploadExcel(formData);
        if (response.error) {
            option.onError(response.error);
        } else {
            option.onSuccess();
        }
    };

    const uploadProps: UploadProps = {
        accept: '.xlsx, .xls',
        customRequest,
        maxCount: 1,
        style: { width: '50vw' },
    };

    return (
        <div>
            <Upload.Dragger {...uploadProps}>上传本地文件</Upload.Dragger>
        </div>
    );
};

export default Page;

二. ServerAction 处理

首先安装xlsx,处理excel文件

npm i xlsx

其次编写ServerAction:

'use server';

import * as XLSX from 'xlsx';

export const uploadExcel = async (formData: FormData) => {
    // 拿到 file
    const file = formData.get('file') as File;
    let data: any[] = [];
    try {
    	// 要拿到对应的buffer流(直接用file是不行的)
        const bytes = await file.arrayBuffer();
        const content = Buffer.from(bytes);
        // 读取文件
        const workbook = XLSX.read(content, { type: 'buffer' });
        // 拿到所有 sheet
        const workSheets = workbook.Sheets;
        // 拿到第一个 sheet 的数据 
        data = XLSX.utils.sheet_to_json(workSheets[workbook.SheetNames[0]]);
    } catch (e) {
        console.error(e);
    }
    // 打印数据
    console.log(data);
    return data;
};

;