使用 bind 绑定上传档案栏位变数
使用 $
监听档案变数异动,再执行档案存取即可
<script>
let files;
$: if (files) {
// Note that `files` is of type `FileList`, not an Array:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
console.log(files);
for (const file of files) {
console.log(`${file.name}: ${file.size} bytes`);
}
}
</script>
<label for="avatar">Upload a picture:</label>
<input accept="image/png, image/jpeg" bind:files id="avatar" name="avatar" type="file" />
<label for="many">Upload multiple files of any type:</label>
<input bind:files id="many" multiple type="file" />
{#if files}
<h2>Selected files:</h2>
{#each Array.from(files) as file}
<p>{file.name} ({file.size} bytes)</p>
{/each}
{/if}
使用 SheetJS 载入 Excel
载入传入的 input file 档案
function handleDrop(e) {
e.stopPropagation(); e.preventDefault();
var f = e.dataTransfer.files[0];
/* f is a File */
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
/* reader.readAsArrayBuffer(file) -> data will be an ArrayBuffer */
var workbook = XLSX.read(data);
/* DO SOMETHING WITH workbook HERE */
};
reader.readAsArrayBuffer(f);
}
drop_dom_element.addEventListener("drop", handleDrop, false);
使用 Svelte 与 SheetJS 载入 Excel 档案
使用
XLSX.utils.sheet_to_json
函式载入 Excel 档案成JSON
物件时,预设会将第一列当作是资料的key
,所以第一列不要放资料,放用于程式识别的键值
<script>
import * as XLSX from "xlsx";
let input_files;
$: if (input_files) {
try {
// Get the first file
const input_file = event.target.files[0];
// Print file name & size
console.log(`${input_file.name}: ${input_file.size} bytes`);
// Set file reader
const reader = new FileReader();
// Set onload function and call file reader
reader.onload = function (e) {
var data = e.target.result;
/* reader.readAsArrayBuffer(file) -> data will be an ArrayBuffer */
var LoadedXLSX = XLSX.read(data);
// Transform first sheet to json
const load_data_list = XLSX.utils.sheet_to_json(
LoadedXLSX.Sheets[LoadedXLSX.SheetNames[0]],
);
console.log(load_data_list);
};
reader.readAsArrayBuffer(input_file);
} catch (error) {
console.log(error);
alert("Read file failure");
}
}
</script>
<input bind:files={input_files} id="file_input" name="file_input" type="file" />
Reference
- File inputs • REPL • Svelte
- xlsx - npm
- SheetJS Community Edition | SheetJS Community Edition
- Sheets in Svelte Sites | SheetJS Community Edition
- Top 5 Javascript CSV Parsers
Donate KJ 贊助作者喝咖啡
如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method | 贊助 Donate |
PayPal | https://paypal.me/kejyun |
綠界 ECPay | https://p.ecpay.com.tw/AC218F1 |
歐付寶 OPay | https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8 |