docs.sheetjs.com/docz/static/server/SheetJSDrash.ts

79 lines
2.4 KiB
TypeScript
Raw Permalink Normal View History

2023-05-03 03:40:40 +00:00
/*! sheetjs (C) SheetJS -- https://sheetjs.com */
// @deno-types="https://cdn.sheetjs.com/xlsx-latest/package/types/index.d.ts"
import { read, utils, write, set_cptable } from 'https://cdn.sheetjs.com/xlsx-latest/package/xlsx.mjs';
import * as cptable from 'https://cdn.sheetjs.com/xlsx-latest/package/dist/cpexcel.full.mjs';
set_cptable(cptable);
2023-10-16 09:12:56 +00:00
import * as Drash from "https://cdn.jsdelivr.net/gh/drashland/drash@v2.8.1/mod.ts";
2023-05-03 03:40:40 +00:00
class ParseResource extends Drash.Resource {
public paths = ["/"];
public POST(request: Drash.Request, response: Drash.Response) {
const file = request.bodyParam<Drash.Types.BodyFile>("file");
if (!file) throw new Error("File is required!");
var wb = read(file.content);
2023-08-18 20:39:12 +00:00
return response.html(utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]));
2023-05-03 03:40:40 +00:00
}
public GET(request: Drash.Request, response: Drash.Response): void {
return response.html(`\
<!DOCTYPE html>
<html>
<head>
<title>SheetJS Spreadsheet to HTML Conversion Service</title>
<meta charset="utf-8" />
</head>
<body>
<pre><h3><a href="//sheetjs.com/">SheetJS</a> Spreadsheet Conversion Service</h3>
<b>API</b>
Send a POST request to http://localhost:7262/ with the file in the "file" body parameter:
$ curl -X POST -F"file=@test.xlsx" http://localhost:7262/
The response will be an HTML TABLE generated from the first worksheet.
<b>Try it out!</b><form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
Use the file input element to select a file, then click "Submit"
<button type="submit">Submit</button>
</form>
</pre>
</body>
</html>`,
);
}
}
class WriteResource extends Drash.Resource {
public paths = ["/export"];
public GET(request: Drash.Request, response: Drash.Response): void {
// create some fixed workbook
const data = ["SheetJS".split(""), [5,4,3,3,7,9,5]];
const ws = utils.aoa_to_sheet(data);
const wb = utils.book_new(); utils.book_append_sheet(wb, ws, "data");
// write the workbook to XLSX as a Uint8Array
const file = write(wb, { bookType: "xlsx", type: "buffer"});
// set headers
response.headers.set("Content-Disposition", 'attachment; filename="SheetJSDrash.xlsx"');
// send data
return response.send("application/vnd.ms-excel", file);
}
}
const server = new Drash.Server({
hostname: "",
port: 7262,
protocol: "http",
resources: [ ParseResource, WriteResource ],
});
server.run();
console.log(`Server running at ${server.address}.`);