How to View XLSX Documents using react-doc-viewer npm

3.1k Views Asked by At

I am trying to render an XLSX file in React, but it is not loading the Excel document when I visit the link in the browser. I have tried using the following code as a sample from an NPM package, but it is not working:

function App() {
    const [selectedDocs, setSelectedDocs] = useState([]);

    return (
        <>
            <input
                type="file"
                accept=".pdf, .docx, .xlsx, .xls"
                multiple
                onChange={(el) =>
                    el.target.files?.length &&
                    setSelectedDocs(Array.from(el.target.files))
                }
            />
            <DocViewer
                documents={selectedDocs.map((file) => ({
                    uri: window.URL.createObjectURL(file),
                    fileName: file.name,
                }))}
                pluginRenderers={DocViewerRenderers}
            />
        </>
    );
}

Could you please help me understand why the XLSX file is not loading? Any guidance or suggestions would be greatly appreciated. Thank you!

1

There are 1 best solutions below

0
TurboLion On

Unfortunately, it is not possible to render a local XLSX file (or any Microsoft Office document) with this library, to quote the library's author:

Office files only work with a public URL. If the URL is not public, accessible directly from the browser, or with some authentication, this won't work.

The reason it that to display Microsoft Office documents the library is using Mircosoft's "view.officeapps.live.com" in an iframe, which needs a publicly hosted file to work, see line 13 in this file in source code: https://github.com/cyntler/react-doc-viewer/blob/8633ec51bb7adc8245faf60f84e9d57a53a2d45e/src/renderers/msdoc/index.tsx#L13

You might have better luck using a library like SheetJS.