-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONtoExcel.ts
88 lines (75 loc) · 2.4 KB
/
JSONtoExcel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import * as Excel from "exceljs/dist/exceljs.min.js"; // Import excel js like this only
import * as FileSaver from "file-saver";
export class JSONtoExcel {
constructor() {}
jsontoExcel() {
try {
// Setting Title of Excel
const title = "templateName";
// Setting header
const sheetName = "templateName";
// Setting sub-header
const subTitleRow1 = [
"TestName : ",
"Abhishek",
,
,
"Date : ",
new Date()
];
const subTitleRow2 = ["College Name : ", "NIT Raipur"];
// Setting Header
const header = ["Lang1", "Lang2", "Lang3", "Lang4"];
console.log("Header:::::", header);
// Creating workbook
const workbook = new Excel.Workbook();
// Creating sheet in workbook
const worksheet = workbook.addWorksheet(sheetName);
// Setting the Width
for (let i = 0; i < header.length; i++) {
worksheet.getColumn(1 + i).width = 20; // 20 Hardcoded
}
// Adding title and applying styles to it.
const titleRow = worksheet.addRow([title]);
titleRow.font = { name: "Calibri", family: 4, size: 16, bold: true };
worksheet.mergeCells("A1:F2");
worksheet.getCell("A1").alignment = {
vertical: "middle",
horizontal: "center"
};
// Adding Blank Row
worksheet.addRow([]);
// Adding subtitle row
worksheet.addRow(subTitleRow1);
worksheet.addRow([]);
worksheet.addRow(subTitleRow2);
worksheet.addRow([]);
// Adding header row
const headerRow = worksheet.addRow(header);
headerRow.eachCell((cell, number) => {
cell.border = {
top: { style: "thin" },
left: { style: "thin" },
bottom: { style: "thin" },
right: { style: "thin" }
};
cell.font = { bold: true, size: 12 };
});
// Adding the data
worksheet.addRows([
["C", "JAVA", "TYPESCRIPT", "NODE"],
["PYTHON", "SQL", "ANGULAR", "REACT"]
]);
// Downloading the file
workbook.xlsx.writeBuffer().then(resData => {
const blob = new Blob([resData], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
FileSaver.saveAs(blob, sheetName + ".xlsx");
});
} catch (error) {
console.log("Error occured while genarating excel report", error);
}
}
}