0
2

More than 1 year has passed since last update.

【Node.js】Node.jsでExcelのフォーマットを崩さず加工

Last updated at Posted at 2022-07-21

導入:スマホアプリエンジニア目線

×:スマホアプリ内部でフォーマットを崩さずにエクセルを編集・書き出しをする
○:サーバーサイドでエクセルの編集・書き出し(アプリにレスポンスでExcelを投げる)をする

早速Node.js + Herokuでアプリを作ることに

Node.jsは初心者なのでお手柔らかに、、(アロー関数等を使えばもっと綺麗になると思います。)
今回は無料で使えるHerokuを用いてサーバーアプリを作ることにしました。
・Heroku
参考:https://jp.heroku.com/free

・Nodeの環境構築
各OSによって違いがあるので今回は省略

・expressを導入(Webフレームワーク)
参考:https://expressjs.com/ja/

・xlsx-populateを導入
参考:https://github.com/dtjohnson/xlsx-populate#xlsx-populate

xlsx-populateに決定した理由

・今回はテンプレートのExcelファイルに追記したいのでフォーマットが崩れないものを選んだ

以下、コードで説明

・導入したフレームワークをインポートする

node.js
const XlsxPopulate = require('xlsx-populate');
const express = require('express');
const app = express();

・JSONオブジェクトを認識するコード
・Herokuで使うためにポート3000番を解放
(他、今回は使わないコードも記載。)

node.js
app.use(express.urlencoded({
    extended: true
}));
app.use(express.json());

app.listen(process.env.PORT || 3000);
console.log('Server is online.');

・スマホアプリからPostでリクエストする
スマホアプリからリクエストするときにbodyにJsonを付与する。

node.js
app.post('/createExcel', function(req, res) {


  console.log(req.body);
  

  const json = req.body;

  //. テンプレート
  const templateFile = './01.xlsx';

  //. 出力先(Herokuではtmp以下にファイルを一時保存する)
  const outputFilePath = '/tmp/' + json.excelName + '.xlsx';

  XlsxPopulate.fromFileAsync(templateFile).then( book => {
    // 0番目のsheetに書き込む
    var sheet1 = book.sheet(0);
    for (const [key, value] of Object.entries(json.cell)) {
      sheet1.cell(key).value(value);
    }
    // outputFilePathnに書き出し
    book.toFileAsync(outputFilePath).then( result => {
      // resで端末にダウンロードさせる
      res.download(outputFilePath);
    });
  });
})

・json一例

{
    "excelName":"書き出したいエクセル名",
    "cell":
    {
        "D8":"D8に入れたい内容",
        "F8":"F8に入れたい内容"
    }
}

コード全体

node.js
const XlsxPopulate = require('xlsx-populate');

const express = require('express');
const app = express();

// urlencodedとjsonは別々に初期化する
app.use(express.urlencoded({
    extended: true
}));
app.use(express.json());

app.listen(process.env.PORT || 3000);
console.log('Server is online.');

app.post('/createExcel', function(req, res) {


  console.log(req.body);
  

  const json = req.body;

  //. テンプレート
  const templateFile = './01.xlsx';

  //. 出力先
  const outputFilePath = '/tmp/' + json.excelName + '.xlsx';

  XlsxPopulate.fromFileAsync(templateFile).then( book => {
    var sheet1 = book.sheet(0);
    for (const [key, value] of Object.entries(json.cell)) {
      sheet1.cell(key).value(value);
    }

    book.toFileAsync(outputFilePath).then( result => {
      res.download(outputFilePath);
    });
  });
})

できそうなこと・今回妥協したこと

・文字、Cell等にプロパティをつける
・入力した値でExcel内のマクロ(関数)を実行させる

アロー関数使ったら!と意見がありましたので時間見つけて修正しておきます。

最後に

iOSアプリ開発をしています。
主にSwiftですが、最近は熱が入ってきてFlutterも🦾
色々やってます。もし良かったら見てってください。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2