Skip to content

Commit 0a9cb21

Browse files
authored
Excel service to create and publiish
Excel service to create and publiish
1 parent 2f3c6f8 commit 0a9cb21

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

excel.service.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { Injectable } from '@angular/core';
2+
import {saveAs} from 'file-saver';
3+
import { WorkBook, read, utils, write, readFile } from 'xlsx';
4+
@Injectable()
5+
export class FileExcelService {
6+
7+
wbout = [];
8+
table = [];
9+
ws: any;
10+
constructor() {
11+
this.setExcelProperties('');
12+
}
13+
14+
s2ab(s) {
15+
const buf = new ArrayBuffer(s.length);
16+
const view = new Uint8Array(buf);
17+
for (let i = 0; i !== s.length; ++i) {
18+
view[i] = s.charCodeAt(i) & 0xFF;
19+
};
20+
return buf;
21+
}
22+
23+
24+
SaveToExcel(tableData, fileName: string= 'QuestionSheet') {
25+
this.setTableData(tableData,fileName);
26+
saveAs(new Blob([this.s2ab(this.wbout)], { type: 'application/octet-stream' }), fileName+'.xlsx');
27+
}
28+
29+
getTableData()
30+
{
31+
return this.table;
32+
}
33+
34+
setTableData(tableData, fileName: string)
35+
{
36+
this.table = tableData;
37+
this.setExcelProperties(fileName);
38+
}
39+
40+
41+
// excel Detail
42+
setExcelProperties(fileName: string)
43+
{
44+
const ws_name = fileName.substr(0, 25); //'QuestionSheet'
45+
// const ws_name = ''; // worksheet name cannot exceed 31 chracters length
46+
const wb: WorkBook = { SheetNames: [], Sheets: {} };
47+
this.ws = utils.json_to_sheet(this.getTableData());
48+
wb.SheetNames.push(ws_name);
49+
wb.Sheets[ws_name] = this.ws;
50+
this.wbout = write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
51+
}
52+
53+
convertExcelToJson(file)
54+
{
55+
let reader = new FileReader();
56+
let workbookkk;
57+
let XL_row_object;
58+
let json_object;
59+
reader.readAsBinaryString(file);
60+
return new Promise((resolve, reject) => {
61+
reader.onload = function(){
62+
// alert(reader.result);
63+
let data = reader.result;
64+
workbookkk=read(data,{type: 'binary'});
65+
console.log(workbookkk);
66+
workbookkk.SheetNames.forEach(function(sheetName) {
67+
// Here is your object
68+
XL_row_object = utils.sheet_to_json(workbookkk.Sheets[sheetName]);
69+
json_object = JSON.stringify(XL_row_object);
70+
// console.log(json_object);
71+
// console.log(XL_row_object);
72+
resolve(XL_row_object);
73+
});
74+
};
75+
});
76+
}
77+
}

0 commit comments

Comments
 (0)