From 8ed027e61536dc876e3e8bc32ed1b2fc2f156403 Mon Sep 17 00:00:00 2001 From: ofirelarat <96ofir11@gmail.com> Date: Sat, 26 Nov 2022 10:45:11 +0200 Subject: [PATCH] add ability to choose ws --- README.md | 2 ++ src/index.js | 24 ++++++++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d1471cd..31fdf1d 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ import {OutTable, ExcelRenderer} from 'react-excel-renderer'; ``` * In the `onChange` handler, invoke the `ExcelRenderer` function and provide file object from the event handler to the `ExcelRenderer` function to obtain JSON data from sheet + +you can add the parameter `worksheet` to pick specific worksheet in the excel file (by his name or is index), the default is the first one. ``` fileHandler = (event) => { let fileObj = event.target.files[0]; diff --git a/src/index.js b/src/index.js index 4303ac2..1d442fb 100644 --- a/src/index.js +++ b/src/index.js @@ -35,7 +35,7 @@ export class OutTable extends Component { } } -export function ExcelRenderer(file, callback) { +export function ExcelRenderer(file, callback, worksheet) { return new Promise(function(resolve, reject) { var reader = new FileReader(); var rABS = !!reader.readAsBinaryString; @@ -44,9 +44,8 @@ export function ExcelRenderer(file, callback) { var bstr = e.target.result; var wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" }); - /* Get first worksheet */ - var wsname = wb.SheetNames[0]; - var ws = wb.Sheets[wsname]; + /* Get worksheet */ + var ws = get_worksheet(worksheet); /* Convert array of arrays */ var json = XLSX.utils.sheet_to_json(ws, { header: 1 }); @@ -70,3 +69,20 @@ export function ExcelRenderer(file, callback) { } return o; } + + function get_worksheet(worksheet) { + /* Get worksheet with default as fisrt worksheet */ + const default_wsname = wb.SheetNames[0]; + let pickedWorksheet = wb.Sheets[default_wsname]; + + if(worksheet){ + if(typeof(worksheet) === 'number'){ + const wsname = wb.SheetNames[worksheet]; + pickedWorksheet = wb.Sheets[wsname]; + }else{ + pickedWorksheet = wb.Sheets[worksheet]; + } + } + + return pickedWorksheet; + } \ No newline at end of file