2023-05-22 08:06:09 +00:00
|
|
|
/*! sheetjs (C) SheetJS -- https://sheetjs.com */
|
|
|
|
use std::path::Path;
|
|
|
|
use std::string::String;
|
|
|
|
use std::fs;
|
|
|
|
|
2024-03-16 16:04:18 +00:00
|
|
|
use boa_engine::{js_string, Context, Source, JsError};
|
2023-05-22 08:06:09 +00:00
|
|
|
use boa_engine::object::builtins::JsArrayBuffer;
|
|
|
|
use boa_engine::property::Attribute;
|
|
|
|
|
|
|
|
fn eval_file(c: &mut Context, path: &str) -> Result<String, JsError> {
|
|
|
|
let src = Source::from_filepath(Path::new(path)).unwrap();
|
2023-06-05 20:12:53 +00:00
|
|
|
match c.eval(src) {
|
2023-05-22 08:06:09 +00:00
|
|
|
Ok(res) => { return Ok(res.to_string(c).unwrap().to_std_string_escaped()); }
|
|
|
|
Err(e) => { return Err(e); }
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
fn eval_code(c: &mut Context, code: &str) -> Result<String, JsError> {
|
|
|
|
let src = Source::from_bytes(code);
|
2023-06-05 20:12:53 +00:00
|
|
|
match c.eval(src) {
|
2023-05-22 08:06:09 +00:00
|
|
|
Ok(res) => { return Ok(res.to_string(c).unwrap().to_std_string_escaped()); }
|
|
|
|
Err(e) => { return Err(e); }
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let context = &mut Context::default();
|
|
|
|
|
|
|
|
/* load library */
|
|
|
|
match eval_file(context, "./xlsx.full.min.js") {
|
|
|
|
Ok(_res) => {}
|
|
|
|
Err(e) => { return eprintln!("Uncaught {e}"); }
|
|
|
|
}
|
|
|
|
|
|
|
|
/* get version string */
|
|
|
|
match eval_code(context, "XLSX.version") {
|
|
|
|
Ok(res) => { println!( "SheetJS library version {}", res); }
|
|
|
|
Err(e) => { return eprintln!("Uncaught {e}"); }
|
|
|
|
}
|
|
|
|
|
|
|
|
/* read file */
|
|
|
|
let data: Vec<u8> = fs::read("pres.xlsx").unwrap();
|
|
|
|
let array: JsArrayBuffer = JsArrayBuffer::from_byte_block(data, context).unwrap();
|
|
|
|
let attrs = Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE;
|
2024-03-16 16:04:18 +00:00
|
|
|
context.register_global_property(js_string!("buf"), array, attrs);
|
2023-05-22 08:06:09 +00:00
|
|
|
|
|
|
|
/* parse workbook and assign to global `wb` property */
|
|
|
|
match eval_code(context, "void (globalThis.wb = XLSX.read(buf))") {
|
|
|
|
Ok(_res) => { }
|
|
|
|
Err(e) => { return eprintln!("Uncaught {e}"); }
|
|
|
|
}
|
|
|
|
|
|
|
|
/* print CSV of first worksheet */
|
|
|
|
match eval_code(context, "XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]])") {
|
|
|
|
Ok(res) => { println!( "{}", res); }
|
|
|
|
Err(e) => { return eprintln!("Uncaught {e}"); }
|
|
|
|
}
|
|
|
|
}
|