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

主宰稳场 提交于 2020-12-15 05:29:41

问题


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

  • https://github.com/webodf/WebODF
  • https://www.npmjs.com/package/simple-odf

回答1:


Thanks to the comment of DigitalDrifter 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 fro 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);
            }
        }) ;  
       
    }


来源:https://stackoverflow.com/questions/64842218/how-to-read-and-process-open-document-spreadsheet-ods-files-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!