Phú Nguyễn

26 bundles
1 file3 months ago
4

Read Excel and write JSON

index.js

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566const _ = require("lodash");
const ExcelJS = require("exceljs");
const fs = require("fs-extra");

const XlsxFile = "./Book1.xlsx";

function readExcelFilesAndOutputJSON() {
    const workBookExt = /[^/]*$/
        .exec(require("url").parse(XlsxFile).pathname)[0]
        .substr(
            /[^/]*$/
                .exec(require("url").parse(XlsxFile).pathname)[0]
                .indexOf(".") + 1
        );

    const workBook =
        workBookExt === "csv"
            ? new ExcelJS.Workbook().csv.readFile(XlsxFile)
            : new ExcelJS.Workbook().xlsx.readFile(XlsxFile);

    workBook
        .then(data => {
            const langSheet =
                workBookExt === "csv"
                    ? data.getSheetValues()
                    : data.worksheets[0].getSheetValues();

            const rows = langSheet
                .map((row, index) => {
                    console.log("Reading row ", index, row);
                    if (!row) console.log("Row", index, "is empty, passed.");
                    else return row;
                })
                .filter(row => row)
                .map(row => row.filter(cell => _.trim(cell)));

            const langs = rows[0].filter(
                (lang, index) => index > 0 && lang !== "END"
            );

            const keys = langs.map((lang, index) => {
                let temp = {};
                rows.forEach((row, i) => {
                    if (i) temp = _.merge(temp, { [row[0]]: row[index + 1] });
                });

                if (!_.isEmpty(temp)) return temp;
            });

            langs.forEach((lang, index) => {
                fs.outputJSON(`./${lang}/common.json`, keys[index])
                    .then(() => {
                        console.log("Success write", lang, "json.");
                    })
                    .catch(err => {
                        console.log(err);
                    });
            });
        })
        .catch(error => {
            console.log(error);
        });
}

readExcelFilesAndOutputJSON();