Bootstrap

nextjs当后端使-读取excel文件

目前nextjs有种php的感觉,现在的需求是读取excel文件,入数据库,拆分出读取excel的代码如下:

import { NextRequest } from "next/server";
import { join } from "path";
import { readFile } from "fs/promises";
import * as XLSX from "xlsx";

export async function POST(req: NextRequest) {
  const uploadDir = join(process.cwd(), "public", "/assets");
  const filepath = `${uploadDir}/wp_postmeta.xlsx`;

  try {
    const fileContent = await readFile(filepath);
    const workbook = XLSX.read(fileContent, { type: "buffer" });
    const sheetName = workbook.SheetNames[0]; // Assuming there's only one sheet
    const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
    console.log(sheetData);

    return new Response(JSON.stringify({ message: "文件处理成功" }), {
      status: 200,
    });
  } catch (error) {
    console.error("Error reading or processing XLSX file:", error);
    return new Response(JSON.stringify({ error: "文件处理错误" }), {
      status: 500,
    });
  }
}

;