如何使用 Javascript 保存 excel 工作簿

How to save excel workbook using Javascript

我创建了一个 HTML 表单来接收用户数据,并使用 exceljs 和其他一些库将这些数据存储到 excel 电子表格中。我的这部分代码工作得很好。但是,当我刷新服务器时,之前存储在 excel 文件中的数据被删除了。

我相信原因是我无法保存 excel 工作簿....但是当我搜索一些代码来实现它并执行它时...代码不起作用。

以下是将用户数据收集到 excel 工作表中的代码:

//importing necessary libraries
const express = require("express");
const morgan = require("morgan");
const Prohairesis = require("prohairesis");
const bodyParser = require("body-parser");
const Excel = require("exceljs");

const app  = express();
const port = process.env.PORT || 8081;

var info = []

app
    .use(express.static('public'))
    .use(morgan('dev'))
    .use(bodyParser.urlencoded({extended: false}))
    .use(bodyParser.json())

    .post('/api/user', (req, res) => {

        res.json(req.body);

        //collecting user data into a javascript string 
        const user = req.body;
        const ud = JSON.stringify(user);
        const user_data = JSON.parse(ud);
        console.log(user_data);
        const user_li = [user_data.first, user_data.email, user_data.stdid, user_data.pwd, user_data.cpwd];
        console.log(user_li);

        //some simple validation
        for (i in user_li)
        {
            if (user_data.pwd != user_data.cpwd)
            {
                console.log("**Password does not match**");
                break;
            }
            if (user_data.pwd == user_data.cpwd)
            {
                info.push(user_li);
                console.log(info);
               
                //append row to excel worksheet
                const workbook = new Excel.Workbook();
                const worksheet = workbook.addWorksheet('Main Db');
                worksheet.addRows(info);
                workbook.xlsx.writeFile("Login-Db.xlsx")
                console.log('Row has been appended');
                break;
            }
        }

    })

    .listen(port, () => console.log('Server listening on port ${port}'));

您的代码运行良好。问题是,每次重新启动服务器时,您都会重新创建一个同名的新 excel 文件。

您必须实施一些额外的逻辑来检查文件是否已存在于服务器中。如果是这样,则不要创建文件,只需将新行附加到现有文件,否则创建一个新文件并保存数据。

我添加了以下工作示例:

//importing necessary libraries
const express = require("express");
const morgan = require("morgan");
const Prohairesis = require("prohairesis");
const bodyParser = require("body-parser");
const Excel = require("exceljs");
const fs = require("fs");

const app = express();
const port = process.env.PORT || 4444;

let info = [];

app
  .use(express.static("public"))
  .use(morgan("dev"))
  .use(bodyParser.urlencoded({ extended: false }))
  .use(bodyParser.json())

  .post("/api/user", async (req, res) => {
    res.json(req.body);

    //collecting user data into a javascript string
    const user = req.body;
    const ud = JSON.stringify(user);
    const user_data = JSON.parse(ud);
    console.log(user_data);
    const user_li = [
      user_data.first,
      user_data.email,
      user_data.stdid,
      user_data.pwd,
      user_data.cpwd,
    ];
    console.log(user_li);

    //some simple validation
    for (i in user_li) {
      if (user_data.pwd != user_data.cpwd) {
        console.log("**Password does not match**");
        break;
      }
      if (user_data.pwd == user_data.cpwd) {
        info.push(user_li);
        console.log(info);

        //append row to excel worksheet
        const workbook = new Excel.Workbook();
        // for safety
        try {
          // check if `Login-Db.xlsx` file exists
          if (fs.existsSync("Login-Db.xlsx")) {
            // load existing workbook
            workbook.xlsx.readFile("Login-Db.xlsx").then((workbook) => {
              // get worksheet
              const worksheet = workbook.getWorksheet("Main Db");
              // append rows to worksheet
              worksheet.addRows(info);
              // save workbook
              workbook.xlsx.writeFile("Login-Db.xlsx").then((err) => {
                if (!err) {
                  console.log("Row added to excel file");
                  return;
                }
                // if error, print it
                console.log(err);
              });
            });
          } else {
            // create new worksheet
            const worksheet = workbook.addWorksheet("Main Db");
            // add new rows to worksheet
            worksheet.addRows(info);
            // save workbook
            workbook.xlsx.writeFile("Login-Db.xlsx").then((err) => {
              if (!err) {
                console.log("Row added to excel file");
                return;
              }
              // if error, print it
              console.log(err);
            });
          }
        } catch (error) {
          console.log(error);
        }
        break;
      }
    }
  })

  .listen(port, () => console.log(`Server listening on port ${port}`));

备注(额外):

  • 您的行实际上是在您执行 worksheet.addRows(info);

    时添加的
  • 在检查 fs 之前使用 try/catch

  • docs 中提到写入 xlsx 文件是异步的,因此应该使用 await。所以在安全保存文件后使用async/await记录结果。

// using async/await

.post("/api/user", async (req, res) => {
  // other code
  await workbook.xlsx.writeFile("Login-Db.xlsx");
}

// or using .then()

workbook.xlsx.writeFile("Login-Db.xlsx").then(() => {
  console.log("File has been written");
});