【发布时间】:2020-05-13 15:39:26
【问题描述】:
我到处寻找解决方案。在 javascript 中编写新的 xlsx 文件时,如何向单元格添加样式? 当我的意思是样式时,我想在第一行(A1)中添加背景颜色,并且还希望所有工作表都是 RTL 而不是 LTR 我在文档中进行了搜索,但未能成功实施此选项 如果有人能提出解决这个问题的方法,我将不胜感激
这是我的脚本:
function getCsvFile(value) {
const currentDate = getCurrentDate()
let obj = []
let currentCompany = ''
value.split('\n').forEach(row => {
let i = 0;
if (!row.startsWith('[') && !row.startsWith(']')) {
if (!hasNumber(row.split(' ')[0])) {
currentCompany = row
const isExists = obj.find(company => company.name === currentCompany)
if (isExists) {
} else {
obj.push({ name: currentCompany, products: [] })
}
} else {
obj = obj.map(company => company.name === currentCompany ? { ...company, products: [...company.products, row] } : company)
}
}
});
const maxRows = Math.max.apply(Math, obj.map(function (o) { return o.products.length; }))
const headers = obj.map(({ name }) => name)
let rows = []
for (let i = 0; i < maxRows; i++) {
let row = []
obj.forEach(element => {
row.push(element.products[i] || '')
});
rows.push(row)
}
var wb = XLSX.utils.book_new();
wb.Props = {
Title: "SheetJS Tutorial",
Subject: "Test",
Author: "Red Stapler",
CreatedDate: new Date(2017, 12, 19)
};
wb.SheetNames.push(currentDate);
var ws_data = [
headers,
...rows
];
var ws = XLSX.utils.aoa_to_sheet(ws_data);
ws['A1'].s = {
fill: {
patternType: "none", // none / solid
fgColor: { rgb: "FF000000" },
bgColor: { rgb: "FFFFFFFF" }
},
font: {
name: 'Times New Roman',
sz: 16,
color: { rgb: "#FF000000" },
bold: true,
italic: false,
underline: false
},
border: {
top: { style: "thin", color: { auto: 1 } },
right: { style: "thin", color: { auto: 1 } },
bottom: { style: "thin", color: { auto: 1 } },
left: { style: "thin", color: { auto: 1 } }
}
};
var wscols = headers.map(column => {
return { wch: column.length + 20 }
});
ws['!cols'] = wscols;
wb.Sheets[currentDate] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary', });
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 'test.xlsx');
}
非常感谢!
【问题讨论】:
标签: javascript excel xlsx