在Javascript / React / Node中是否可以实现此功能?
假设我有一个对象数组:
var obj = [ {'date' : 01/01/2019, 'value': 1}, {'date' : 02/01/2019, 'value': 2}, {'date' : 03/01/2019, 'value': 3}]
然后我想将每个对象的值字段及其相应的日期值写入到现有的excel文件中。
从此excel文件中:
下面的这个:
这在JS中可以实现吗?谢谢。
答案 0 :(得分:0)
是的,可以做您想做的事。
如果您使用的是nodejs,则可以安装此软件包https://www.npmjs.com/package/xlsx
这是一个如何读取值的示例代码
'use strict'
const XLSX = require('xlsx');
const workbook = XLSX.readFile('./test.xlsx');
var stream = XLSX.stream.to_json(workbook, {raw:true});
const workSheet = workbook.Sheets.Sheet1;
console.log(workSheet["!ref"]);
//With this function you can see the range of your sheet that had data
//You can create a function to parse this information
//and obtain the range of cell where you want to obtain the values
const valuesRange = ['A1', 'B1', 'C1', 'D1'];
let desiredCell = [];
valuesRange.forEach(cell => desiredCell.push(workSheet[cell]));
const desiredValues = (desiredCell ? desiredCell.map(cell => cell.w) : undefined);
console.log(desiredValues);
// This will return [ '1-Jan-19', '2-Jan-19', '3-Jan-19' ]
//Know you can do whatever you want with this values
// example a parse function to convert to 01/01/2019 and write to new file
如果您可以使用Google电子表格,我建议您这样做。
书写和阅读功能非常简单。 您将需要安装https://www.npmjs.com/package/util和https://www.npmjs.com/package/googleapis
const { google } = require('googleapis');
const util = require('util');
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
module.exports = class SpreadSheetService {
constructor(spreadsheetId) {
this.spreadsheetId = spreadsheetId;
this.jwt = new google.auth.JWT(<UserEmail>, null, <Base64Key>, SCOPES);
this.sheets = google.sheets({ version: 'v4', auth: this.jwt });
this.readSpreadSheet = util.promisify(this.sheets.spreadsheets.values.get);
this.updateSpreadSheet = util.promisify(this.sheets.spreadsheets.values.update);
}
async read(sheet, cell) {
return this.readSpreadSheet({
spreadsheetId: this.spreadsheetId,
range: `${sheet}!${cell}`,
valueRenderOption: 'UNFORMATTED_VALUE'
});
}
async write(sheet, cell, value) {
return this.updateSpreadSheet({
spreadsheetId: this.spreadsheetId,
valueInputOption: 'USER_ENTERED',
range: `${sheet}!${cell}`,
resource: { values: [[value]] }
});
}
};