vue-i18n 翻译之 excel 解析

该博客介绍了一个使用node-xlsx和fs模块解析Excel文件,将内容转换为vue-i18n语言包的流程。通过创建一个Translate类,实现了读取Excel,解析工作表并生成JSON文件的功能,从而自动化处理多语言资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

vue-i18n使用excel编写转换成对应语言包:

const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');

const sourcePath = './';
const savePath = '../src/language/package';
const excelName = 'a.xlsx';

class Translate {
  constructor() {
    this.contents = {};
    this.languages = [];
    this.sheets = undefined;
  }
  parseExcel(sourcePath, excelName) {
    this.sheets = xlsx.parse(fs.readFileSync(path.join(__dirname, sourcePath, excelName)));
    this.sheets.forEach(this.parseSheet.bind(this));
    return this;
  }
  parseSheet(sheet) {
    let {data, name} = sheet;
    data.forEach((row, rowIndex) => {
      let key;
      row.forEach((col, colIndex) => {
        // 第一行,文件名
        if (rowIndex === 0 && colIndex !== 0) {
          if (!(col in this.contents)) {
            this.contents[col] = {};
            this.languages.push(col);
          }
        }
        
        if (rowIndex >= 1) {
          if (colIndex === 0) {
            key = col;
          } else {
            const lang = this.languages[colIndex - 1];
            this.contents[lang][`${name}_${key}`] = col;
          }
        }
      })
    });
    
    return this;
  }
  generatorJson(savePath) {
    Object.keys(this.contents).forEach(key => {
      const targetPath = path.resolve(__dirname, savePath, `${key}.json`);
      fs.writeFile(targetPath, JSON.stringify(this.contents[key], null, 2), res => {
        console.log(`translate ${key} success`);
      })
    })
  }
}

new Translate().parseExcel(sourcePath, excelName).generatorJson(savePath);

最终生成的json文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值