forked from SheetJS/sheetjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nscript.ts
83 lines (67 loc) · 2.75 KB
/
nscript.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
/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
import { Component } from "@angular/core";
import * as dockModule from "tns-core-modules/ui/layouts/dock-layout";
import * as buttonModule from "tns-core-modules/ui/button";
import * as textModule from "tns-core-modules/text";
import * as dialogs from "ui/dialogs";
import * as fs from "tns-core-modules/file-system";
/* NativeScript does not support import syntax for npm modules */
const XLSX = require("./xlsx.full.min.js");
@Component({
selector: "my-app",
template: `
<GridLayout rows="auto, *, auto">
<ActionBar row="0" title="SheetJS NativeScript Demo" class="action-bar"></ActionBar>
<!-- data converted to HTML and rendered in web view -->
<WebView row="1" src="{{html}}"></WebView>
<DockLayout row="2" dock="bottom" stretchLastChild="false">
<Button text="Import File" (tap)="import()" style="padding: 10px"></Button>
<Button text="Export File" (tap)="export()" style="padding: 10px"></Button>
</DockLayout>
</GridLayout>
`
})
export class AppComponent {
html: string = "";
constructor() {
const ws = XLSX.utils.aoa_to_sheet([[1,2],[3,4]]);
this.html = XLSX.utils.sheet_to_html(ws);
};
/* Import button */
async import() {
const filename: string = "SheetJSNS.xlsx";
/* find appropriate path */
const target: fs.Folder = fs.knownFolders.documents() || fs.knownFolders.ios.sharedPublic();
const url: string = fs.path.normalize(target.path + "///" + filename);
const file: fs.File = fs.File.fromPath(url);
try {
/* get binary string */
const bstr: string = await file.readText(textModule.encoding.ISO_8859_1);
/* read workbook */
const wb = XLSX.read(bstr, { type: "binary" });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
/* update table */
this.html = XLSX.utils.sheet_to_html(ws);
dialogs.alert(`Attempting to read to SheetJSNS.xlsx in ${url}`);
} catch(e) {
dialogs.alert(e.message);
}
};
/* Export button */
async export() {
const wb = XLSX.read(this.html, { type: "string" });
const filename: string = "SheetJSNS.xlsx";
/* generate binary string */
const wbout: string = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
/* find appropriate path */
const target: fs.Folder = fs.knownFolders.documents() || fs.knownFolders.ios.sharedPublic();
const url: string = fs.path.normalize(target.path + "///" + filename);
const file: fs.File = fs.File.fromPath(url);
/* attempt to save binary string to file */
await file.writeText(wbout, textModule.encoding.ISO_8859_1);
dialogs.alert(`Wrote to SheetJSNS.xlsx in ${url}`);
};
}