vue3的setup语法糖上传Excel文件后端解析数据

前端
<template>
  <div>
    <input type="file" ref="fileInput" @change="handleFileChange" />
    <button @click="uploadFile">Upload File</button>
    <div v-if="uploadResult">
      <p>Upload Result: {{ uploadResult }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
const fileInput = ref(null);
const uploadResult = ref(null);

const handleFileChange = () => {
  // 可选:处理文件选择的逻辑
};

const uploadFile = async () => {
  const formData = new FormData();
  formData.append("file", fileInput.value.files[0]);

  try {
    const response = await axios.post(
      "http://localhost:3000/upload",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );
    uploadResult.value = response.data.message; // 假设后端返回一个包含上传结果的消息
  } catch (error) {
    console.error("Error uploading file:", error);
    uploadResult.value = "Upload failed";
  }
};
</script>

<style lang="scss" scoped>
</style>

后端

const express = require('express');
const router = express.Router();
const multer = require('multer');
const xlsx = require('xlsx'); // 用于解析 Excel 文件
// 设置存储文件的目录和文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'upload/')  // 存储到 uploads 目录
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname) // 保留原始文件名
    }
});

// 创建 multer 实例
const upload = multer({ storage: storage });

router.post('/upload', upload.single('file'), (req, res) => {
    try {
        const filePath = req.file.path; // 上传文件的路径
        const workbook = xlsx.readFile(filePath); // 使用 xlsx 库读取 Excel 文件
        const sheetName = workbook.SheetNames[0]; // 假设只有一个工作表
        const worksheet = workbook.Sheets[sheetName];
        const data = xlsx.utils.sheet_to_json(worksheet);

        // 返回解析后的数据
        console.log('接收数据成功', data);
        res.json({ data });
    } catch (error) {
        console.error('Error parsing Excel file:', error);
        res.status(500).json({ error: 'Failed to parse Excel file' });
    }
});

module.exports = router;

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值