Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ability to choose ws #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {OutTable, ExcelRenderer} from 'react-excel-renderer';
<input type="file" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}} />
```
* 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];
Expand Down
24 changes: 20 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 });
Expand All @@ -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;
}