javascriptodsopendocument

How to read and process Open Document Spreadsheet (*.ods) files with javascript?


I am able to read and process *.xlsx files using an input element of type file and the library exceljs. Also see example code below.

Unfortunately, exceljs does not seem to support open document spreadsheet files *.ods. (The worksheet is undefined).

=> How can I read and process *.ods files with javascript?

https://github.com/exceljs/exceljs

https://github.com/exceljs/exceljs/issues/716

static async readFile(file){
        
        await this.__initializeExcel();
       
        const workbook = new Excel.Workbook();
        await workbook.xlsx.load(file);

        const worksheet = workbook.worksheets[0];

        var data = [];
        const numberOfRows = worksheet.rowCount;
        for (let rowIndex = 1; rowIndex <= numberOfRows; rowIndex++) {
          const row = worksheet.getRow(rowIndex);
          const rowValues = row.values;
          data.push(rowValues);
          rowValues.shift();          
        }

        return data;
    }

Related


Solution

  • Thanks to the comment of Brian I managed to read and process *.ods files with sheetjs/xlsx:

    https://github.com/SheetJS/sheetjs

    npm install xlsx --save 
    

    If you use script tags for import, please make sure to import xlsx.full.min.js instead of xlsx.min.js. Otherwise you'll get an error Cannot find file [Content_Types].xml in zip.

    static async readOdsFile(file){
            
            await this.__initializeXlsx();  //imports xlsx.full.min.js by script tag
          
            return new Promise((resolve, reject)=>{
                var reader = new FileReader();
                reader.onload = event =>  {
                    try{
                        var result = reader.result;
                        var dataArray = new Uint8Array(result);
                        var workbook = Xlsx.read(dataArray, {type: 'array'});
    
                        const firstSheetName = workbook.SheetNames[0];  
                        const worksheet = workbook.Sheets[firstSheetName];
                        const data = Xlsx.utils.sheet_to_json(worksheet,{header:1});                
                    resolve(data); 
                    } catch(error){
                        reject(error);
                    }
                   
                };
    
                try{                
                    reader.readAsArrayBuffer(file);
                } catch (error){
                    reject(error);
                }
            }) ;  
           
        }