如何使用flutter读取Excel文件中的按行详细信息?

时间:2019-06-14 11:32:16

标签: android flutter dart

我需要从外部存储读取.xls格式的Excel文件。使用文件选择器,我有它的路径。但是现在的问题是我必须逐行读取excel文件并将其保存在数组中。

我找不到类似于java的poi之类的库。

预期结果应类似于Workbook => sheet1 => row(i)

3 个答案:

答案 0 :(得分:1)

 OutlinedButton(
              
        onPressed: ()  async {

           ByteData data = await rootBundle.load("assets/mydata.xlsx");
           
        _upload(data);
        
     }
)


static Future<void> _upload(var data) async {

 var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

    var excel = Excel.decodeBytes(bytes);
    
     List<dynamic> excelList = [];
     


  for (var table in excel.tables.keys) 
     {

      for(int rowIndex= 1 ;rowIndex <=excel.tables[table].maxRows; rowIndex++) 
      {
      
       Sheet sheetObject = excel['Sheet1'];
         
      var excelfileDetails = new MyExcelTable();

      excelfileDetails.name = sheetObject.cell(CellIndex.indexByColumnRow(columnIndex:0,rowIndex: rowIndex)).value.toString(); 
      excelfileDetails.age = sheetObject.cell(CellIndex.indexByColumnRow(columnIndex:1,rowIndex: rowIndex)).value; 
      excelfileDetails.state = sheetObject.cell(CellIndex.indexByColumnRow(columnIndex:2,rowIndex: rowIndex)).value.toString(); 
      excelfileDetails.country = sheetObject.cell(CellIndex.indexByColumnRow(columnIndex:3,rowIndex: rowIndex)).value.toString(); 
      excelfileDetails.occupation = sheetObject.cell(CellIndex.indexByColumnRow(columnIndex:4,rowIndex: rowIndex)).value.toString();  
     
      excelList.add(excelfileDetails);
     
     
    }
  }  
}


    class MyExcelTable
    {
         var name;

         var age;

         var state;

        var country;

        var occupation;
  

    MyExcelTable({this.name, this.age, this.state, this.country, this.occupation});

}

答案 1 :(得分:0)

是否必须是Excel文件,或者也可以将其另存为.csv数据?如果您可以将其另存为.csv,则只需将其读取为普通文本即可。

答案 2 :(得分:0)

尝试一下:https://pub.dev/packages/spreadsheet_decoder

import 'dart:io';
import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';

main() {
  var bytes = new File.fromUri(fullUri).readAsBytesSync();
  var decoder = new SpreadsheetDecoder.decodeBytes(bytes);
  var table = decoder.tables['Sheet1'];
  var values = table.rows[0];
  ...
  decoder.updateCell('Sheet1', 0, 0, 1337);
  new File(join(fullUri).writeAsBytesSync(decoder.encode());
  ...
}