0

I have a FileData which is a base64 string and FileType such as as

FileData = "UEsDBBQABgAIAAAAI"

FileType = "application/msexcel"

I want to render this Excel (base64 string) into a react component. I found react-doc-viewer is a good package.

I have written a function that first converts the base64 into a blob and creates a URL that must be given to the DOCViewer component of react-doc-viewer.

function renderPOXLSExcelFile(fileData: any, fileType: any) {

// Convert base64 file data back to a Blob
const binary = atob(fileData.split(',')[1]);
const array = [];
for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
}
const blob = new Blob([new Uint8Array(array)], { type: fileType });

// Create URL from blob
const url = URL.createObjectURL(blob);

const docs = [{ uri: url, fileType: fileType }];

return (
    <>
        <DocViewer documents={docs} config={{header: {disableHeader: false}}}
      pluginRenderers={DocViewerRenderers />
    </>
);
}

The react-doc-viewer is supposed to take uri (URL) as input and show me the excel right. If there is any other approach to render the Excel file from the blob, please let me know.

I have tried parsing the Excel to JSON and applying styles but it looks really bad on UI. Please help me out in finding an approach to this issue.

TIA

1 Answer 1

0

You can use Sheetjs's npm version xlsx.

import * as XLSX from 'xlsx';
//f = file
var name = f.name;
const reader = new FileReader();
reader.onload = (evt) => { // evt = on_file_select event
    /* Parse data */
    const bstr = evt.target.result;
    const wb = XLSX.read(bstr, {type:'binary'});
    /* Get first worksheet */
    const wsname = wb.SheetNames[0];
    const ws = wb.Sheets[wsname];
    /* Convert array of arrays */
    const data = XLSX.utils.sheet_to_csv(ws, {header:1});
    /* Update state */
    console.log("Data>>>"+data);
};
reader.readAsBinaryString(f);

Reference : Reading excel file in Reactjs

Sign up to request clarification or add additional context in comments.

1 Comment

After converting to blob, you can use this code...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.