You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.1 KiB
TypeScript

import nodeXlsx from 'node-xlsx';
import fs from 'fs';
/**
* 生成xlsx
* @param p 生成文件路径
* @param cols 列名
* @param data 行,二维数组
*/
function genXlsx(p, cols, data) {
const d: any = [
{
name: 'Sheet1',
data: [cols, ...data],
},
];
// !cols 指定列的宽度
const buffer = nodeXlsx.build(d, {
'!cols': [{ wch: 60 }, { wch: 20 }],
});
fs.writeFileSync(p, buffer, { flag: 'w' });
}
// 指定单元格内容样式:四个方向的黑边框
const contentCellStyle = {
border: {
top: {
style: 'medium',
color: '#000',
},
bottom: {
style: 'medium',
color: '#000',
},
left: {
style: 'medium',
color: '#000',
},
right: {
style: 'medium',
color: '#000',
},
},
alignment: {
horizontal: 'center',
},
};
// 指定标题单元格样式:加粗居中
const headerStyle = {
font: {
bold: true,
},
alignment: {
horizontal: 'center',
},
};
// genXlsx(
// '1.xlsx',
// [
// {
// v: '表头1',
// s: headerStyle,
// },
// {
// v: '表头2',
// s: headerStyle,
// },
// ],
// [
// [
// {
// v: 123,
// s: contentCellStyle,
// },
// {
// v: 456,
// s: contentCellStyle,
// },
// ],
// ],
// );
export const transColumnXlsx = (data: any[]) => {
return data.map(item => {
return {
v: item,
// s: headerStyle,
};
});
};
export const transRowXlsx = (data: any[][]) => {
const width = 4;
const cols = data[0].map(() => ({ wch: width }));
const new_data = data.map(item => {
const new_item = item.map((index_item, index) => {
if (cols[index].wch < index_item.length * 2) {
cols[index].wch = index_item.length * 2;
}
return {
v: index_item,
s: contentCellStyle,
};
});
return new_item;
});
return { new_data, cols };
};
// export const transRowXlsx = (data: any[]) => {
// return data.map(item => {
// return {
// v: index_item,
// s: contentCellStyle,
// };
// });
// };