Coder Social home page Coder Social logo

excel's Introduction

Excel

Platform Pub Package License: MIT Issues Forks Stars

Excel is a flutter and dart library for reading, creating and updating excel-sheets for XLSX files.

Your Donations will help alot, Thank you!! ❤️❤️

Road-map:

  • ➕ Formulas and Calculations
  • 💾 Support Multiple Data type efficiently
  • 📈 Charts
  • 🌄 Add Pictures
  • 📰 Create Tables and style
  • 🔐 Encrypt and Decrypt excel on the go.
  • Many more features

Breaking changes from 3.x.x to 4.x.x

  • Renamed Formula to FormulaCellValue
  • Cells value now represented by the sealed class CellValue instead of dynamic. Subtypes are TextCellValue FormulaCellValue, IntCellValue, DoubleCellValue, DateCellValue, TextCellValue, BoolCellValue, TimeCellValue, DateTimeCellValue and they allow for exhaustive switch (see Dart Docs (sealed class modifier)).

Breaking changes from 2.x.x to 3.x.x

  • Renamed getColAutoFits() to getColumnAutoFits(), and changed return type to Map<int, bool> in Sheet
  • Renamed getColWidths() to getColumnWidths(), and changed return type to Map<int, double> in Sheet
  • Renamed getColAutoFit() to getColumnAutoFit() in Sheet
  • Renamed getColWidth() to getColumnWidth() in Sheet
  • Renamed setColAutoFit() to setColumnAutoFit() in Sheet
  • Renamed setColWidth() to setColumnWidth() in Sheet

If you find this tool useful, please drop a ⭐️

Usage

Read XLSX File

var file = 'Path_to_pre_existing_Excel_File/excel_file.xlsx';
var bytes = File(file).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
for (var table in excel.tables.keys) {
  print(table); //sheet Name
  print(excel.tables[table].maxColumns);
  print(excel.tables[table].maxRows);
  for (var row in excel.tables[table].rows) {
    for (var cell in row) {
      print('cell ${cell.rowIndex}/${cell.columnIndex}');
      final value = cell.value;
      final numFormat = cell.cellStyle?.numberFormat ?? NumFormat.standard_0;
      switch(value){
        case null:
          print('  empty cell');
          print('  format: ${numFormat}');
        case TextCellValue():
          print('  text: ${value.value}');
        case FormulaCellValue():
          print('  formula: ${value.formula}');
          print('  format: ${numFormat}');
        case IntCellValue():
          print('  int: ${value.value}');
          print('  format: ${numFormat}');
        case BoolCellValue():
          print('  bool: ${value.value ? 'YES!!' : 'NO..' }');
          print('  format: ${numFormat}');
        case DoubleCellValue():
          print('  double: ${value.value}');
          print('  format: ${numFormat}');
        case DateCellValue():
          print('  date: ${value.year} ${value.month} ${value.day} (${value.asDateTimeLocal()})');
        case TimeCellValue():
          print('  time: ${value.hour} ${value.minute} ... (${value.asDuration()})');
        case DateTimeCellValue():
          print('  date with time: ${value.year} ${value.month} ${value.day} ${value.hour} ... (${value.asDateTimeLocal()})');
      }

      print('$row');
    }
  }
}

Read XLSX in Flutter Web

Use FilePicker to pick files in Flutter Web. FilePicker

/// Use FilePicker to pick files in Flutter Web

FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
  type: FileType.custom,
  allowedExtensions: ['xlsx'],
  allowMultiple: false,
);

/// file might be picked

if (pickedFile != null) {
  var bytes = pickedFile.files.single.bytes;
  var excel = Excel.decodeBytes(bytes);
  for (var table in excel.tables.keys) {
    print(table); //sheet Name
    print(excel.tables[table].maxColumns);
    print(excel.tables[table].maxRows);
    for (var row in excel.tables[table].rows) {
      print('$row');
    }
  }
}

Read XLSX from Flutter's Asset Folder

import 'package:flutter/services.dart' show ByteData, rootBundle;

/* Your ......other important..... code here */

ByteData data = await rootBundle.load('assets/existing_excel_file.xlsx');
var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
var excel = Excel.decodeBytes(bytes);

for (var table in excel.tables.keys) {
  print(table); //sheet Name
  print(excel.tables[table].maxColumns);
  print(excel.tables[table].maxRows);
  for (var row in excel.tables[table].rows) {
    print('$row');
  }
}

Create New XLSX File

// automatically creates 1 empty sheet: Sheet1
var excel = Excel.createExcel();

Update Cell values

/*
 * sheetObject.updateCell(cell, value, { CellStyle (Optional)});
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * cell can be identified with Cell Address or by 2D array having row and column Index;
 * Cell Style options are optional
 */

Sheet sheetObject = excel['SheetName'];

CellStyle cellStyle = CellStyle(backgroundColorHex: '#1AFF1A', fontFamily :getFontFamily(FontFamily.Calibri));

cellStyle.underline = Underline.Single; // or Underline.Double


var cell = sheetObject.cell(CellIndex.indexByString('A1'));
cell.value = null; // removing any value
cell.value = TextCellValue('Some Text');
cell.value = IntCellValue(8);
cell.value = BoolCellValue(true);
cell.value = DoubleCellValue(13.37);
cell.value = DateCellValue(year: 2023, month: 4, day: 20);
cell.value = TimeCellValue(hour: 20, minute: 15, second: 5, millisecond: ...);
cell.value = DateTimeCellValue(year: 2023, month: 4, day: 20, hour: 15, ...);
cell.cellStyle = cellStyle;

// setting the number style
cell.cellStyle = (cell.cellStyle ?? CellStyle()).copyWith(

  /// for IntCellValue, DoubleCellValue and BoolCellValue use; 
  numberFormat: CustomNumericNumFormat('#,##0.00 \\m\\²'),

  /// for DateCellValue and DateTimeCellValue use:
  numberFormat: CustomDateTimeNumFormat('m/d/yy h:mm'),

  /// for TimeCellValue use:
  numberFormat: CustomDateTimeNumFormat('mm:ss'),

  /// a builtin format for dates
  numberFormat: NumFormat.standard_14,
  
  /// a builtin format that uses a red text color for negative numbers
  numberFormat: NumFormat.standard_38,

  // The numberFormat changes automatially if you set a CellValue that 
  // does not work with the numberFormat set previously. So in case you
  // want to set a new value, e.g. from a date to a decimal number, 
  // make sure you set the new value first and then your custom
  // numberFormat).
);


// printing cell-type
print('CellType: ' + switch(cell.value) {
  null => 'empty cell',
  TextCellValue() => 'text',
  FormulaCellValue() => 'formula',
  IntCellValue() => 'int',
  BoolCellValue() => 'bool',
  DoubleCellValue() => 'double',
  DateCellValue() => 'date',
  TimeCellValue => 'time',
  DateTimeCellValue => 'date with time',
});

///
/// Inserting and removing column and rows

// insert column at index = 8
sheetObject.insertColumn(8);

// remove column at index = 18
sheetObject.removeColumn(18);

// insert row at index = 82
sheetObject.insertRow(82);

// remove row at index = 80
sheetObject.removeRow(80);

Cell-Style Options

key description
fontFamily eg. getFontFamily(FontFamily.Arial) or getFontFamily(FontFamily.Comic_Sans_MS) There is total 182 Font Families available for now
fontSize specify the font-size as integer eg. fontSize = 15
bold makes text bold - when set to true, by-default it is set to false
italic makes text italic - when set to true, by-default it is set to false
underline Gives underline to text enum Underline { None, Single, Double } eg. Underline.Single, by-default it is set to Underline.None
fontColorHex Font Color eg. '#0000FF'
rotation (degree) rotation of text eg. 50, rotation varies from -90 to 90, with including 90 and -90
backgroundColorHex Background color of cell eg. '#faf487'
wrap Text wrapping enum TextWrapping { WrapText, Clip } eg. TextWrapping.Clip
verticalAlign align text vertically enum VerticalAlign { Top, Center, Bottom } eg. VerticalAlign.Top
horizontalAlign align text horizontally enum HorizontalAlign { Left, Center, Right } eg. HorizontalAlign.Right
leftBorder the left border of the cell (see below)
rightBorder the right border of the cell
topBorder the top border of the cell
bottomBorder the bottom border of the cell
diagonalBorder the diagonal "border" of the cell
diagonalBorderUp boolean value indicating if the diagonal "border" should be displayed on the up diagonal
diagonalBorderDown boolean value indicating if the diagonal "border" should be displayed on the down diagonal
numberFormat a subtype of NumFormat to style the CellValue displayed, use default formats such as NumFormat.standard_34 or create your own using CustomNumericNumFormat('#,##0.00 \\m\\²') CustomDateTimeNumFormat('m/d/yy h:mm') CustomTimeNumFormat('mm:ss')

Borders

Borders are defined for each side (left, right, top, and bottom) of the cell. Both diagonals (up and down) share the same settings. A boolean value true must be set to either diagonalBorderUp or diagonalBorderDown (or both) to display the desired diagonal.

Each border must be a Border object. This object accepts two parameters : borderStyle to select one of the different supported styles and borderColorHex to change the border color.

The borderStyle must be a value from the enumerationBorderStyle:

  • BorderStyle.None
  • BorderStyle.DashDot
  • BorderStyle.DashDotDot
  • BorderStyle.Dashed
  • BorderStyle.Dotted
  • BorderStyle.Double
  • BorderStyle.Hair
  • BorderStyle.Medium
  • BorderStyle.MediumDashDot
  • BorderStyle.MediumDashDotDot
  • BorderStyle.MediumDashed
  • BorderStyle.SlantDashDot
  • BorderStyle.Thick
  • BorderStyle.Thin
/*
 *
 * Defines thin borders on the left and right of the cell, red thin border on the top
 * and blue medium border on the bottom.
 *
 */

CellStyle cellStyle = CellStyle(
  leftBorder: Border(borderStyle: BorderStyle.Thin),
  rightBorder: Border(borderStyle: BorderStyle.Thin),
  topBorder: Border(borderStyle: BorderStyle.Thin, borderColorHex: 'FFFF0000'),
  bottomBorder: Border(borderStyle: BorderStyle.Medium, borderColorHex: 'FF0000FF'),
);

Make sheet RTL

/*
 * set rtl to true for making sheet to right-to-left
 * default value of rtl = false ( which means the fresh or default sheet is ltr )
 *
 */

var sheetObject = excel['SheetName'];
sheetObject.rtl = true;

Copy sheet contents to another sheet

/*
 * excel.copy(String 'existingSheetName', String 'anotherSheetName');
 * existingSheetName should exist in excel.tables.keys in order to successfully copy
 * if anotherSheetName does not exist then it will be automatically created.
 *
 */

excel.copy('existingSheetName', 'anotherSheetName');

Rename sheet

/*
 * excel.rename(String 'existingSheetName', String 'newSheetName');
 * existingSheetName should exist in excel.tables.keys in order to successfully rename
 *
 */

excel.rename('existingSheetName', 'newSheetName');

Delete sheet

/*
 * excel.delete(String 'existingSheetName');
 * (existingSheetName should exist in excel.tables.keys) and (excel.tables.keys.length >= 2), in order to successfully delete.
 *
 */

excel.delete('existingSheetName');

Link sheet

/*
 * excel.link(String 'sheetName', Sheet sheetObject);
 *
 * Any operations performed on (object of 'sheetName') or sheetObject then the operation is performed on both.
 * if 'sheetName' does not exist then it will be automatically created and linked with the sheetObject's operation.
 *
 */

excel.link('sheetName', sheetObject);

Un-Link sheet

/*
 * excel.unLink(String 'sheetName');
 * In order to successfully unLink the 'sheetName' then it must exist in excel.tables.keys
 *
 */

excel.unLink('sheetName');

// After calling the above function be sure to re-make a new reference of this.

Sheet unlinked_sheetObject = excel['sheetName'];

Merge Cells

/*
 * sheetObject.merge(CellIndex starting_cell, CellIndex ending_cell, TextCellValue('customValue'));
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * starting_cell and ending_cell can be identified with Cell Address or by 2D array having row and column Index;
 * customValue is optional
 */

sheetObject.merge(CellIndex.indexByString('A1'), CellIndex.indexByString('E4'), customValue: TextCellValue('Put this text after merge'));

Get Merged Cells List

// Check which cells are merged

sheetObject.spannedItems.forEach((cells) {
  print('Merged:' + cells.toString());
});

Un-Merge Cells

/*
 * sheetObject.unMerge(cell);
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * cell should be identified with string only with an example as 'A1:E4'.
 * to check if 'A1:E4' is un-merged or not
 * call the method excel.getMergedCells(sheet); and verify that it is not present in it.
 */

sheetObject.unMerge('A1:E4');

Find and Replace

/*
 * int replacedCount = sheetObject.findAndReplace(source, target);
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * source is the string or ( User's Custom Pattern Matching RegExp )
 * target is the string which is put in cells in place of source
 *
 * it returns the number of replacements made
 */

int replacedCount = sheetObject.findAndReplace('Flutter', 'Google');

Insert Row Iterables

/*
 * sheetObject.insertRowIterables(list-iterables, rowIndex, iterable-options?);
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * list-iterables === list of iterables which has to be put in specific row
 * rowIndex === the row in which the iterables has to be put
 * Iterable options are optional
 */

/// It will put the list-iterables in the 8th index row
List<CellValue> dataList = [TextCellValue('Google'), TextCellValue('loves'), TextCellValue('Flutter'), TextCellValue('and'), TextCellValue('Flutter'), TextCellValue('loves'), TextCellValue('Excel')];

sheetObject.insertRowIterables(dataList, 8);

Iterable Options

key description
startingColumn starting column index from which list-iterables should be started
overwriteMergedCells overwriteMergedCells is by-defalut set to true, when set to false it will stop over-write and will write only in unique cells

Append Row

/*
 * sheetObject.appendRow(list-iterables);
 * sheetObject created by calling - // Sheet sheetObject = excel['SheetName'];
 * list-iterables === list of iterables
 */

sheetObject.appendRow([TextCellValue('Flutter'), TextCellValue('till'), TextCellValue('Eternity')]);

Get Default Opening Sheet

/*
 * method which returns the name of the default sheet
 * excel.getDefaultSheet();
 */

var defaultSheet = excel.getDefaultSheet();
print('Default Sheet:' + defaultSheet.toString());

Set Default Opening Sheet

/*
 * method which sets the name of the default sheet
 * returns bool if successful then true else false
 * excel.setDefaultSheet(sheet);
 * sheet = 'SheetName'
 */

var isSet = excel.setDefaultSheet(sheet);
if (isSet) {
  print('$sheet is set to default sheet.');
} else {
  print('Unable to set $sheet to default sheet.');
}

Saving

On Flutter Web

// when you are in flutter web then save() downloads the excel file.

// Call function save() to download the file
var fileBytes = excel.save(fileName: 'My_Excel_File_Name.xlsx');

On Android / iOS

For getting saving directory on Android or iOS, Use: path_provider

var fileBytes = excel.save();
var directory = await getApplicationDocumentsDirectory();

File(join('$directory/output_file_name.xlsx'))
  ..createSync(recursive: true)
  ..writeAsBytesSync(fileBytes);

excel's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

excel's Issues

Add support for cell type

Hello,

it would be helpfult if there is a possibility to set a column type. At least to distinguish between text and number cells. This way, it would be easy to perfom math operations with the file afterwards.

Thank you

General column input number would cause error

Attached please find the sample excel, if you put number in general type column would show below error, if you change the input number to any text, the error gone.

sample.xlsx

type '_Smi' is not a subtype of type 'String'
#0 Excel._createCell (package:excel/src/excel.dart:885)
#1 Excel._replaceCell (package:excel/src/excel.dart:874)
#2 Excel._updateCell (package:excel/src/excel.dart:839)
#3 Excel._updateSheetElements. (package:excel/src/excel.dart:415)
#4 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379)
#5 Excel._updateSheetElements (package:excel/src/excel.dart:408)
#6 Excel.encode (package:excel/src/excel.dart:570)
#7 _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:45)
#8 Excel.encode (package:excel/src/excel.dart:559)

excel["filename"] not working in stable channel

Sheet sheet = excel['$filename']; doesn't work in flutter stable channel

Because every version of flutter_test from sdk depends on xml 3.6.1 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4.

Numeric cells

Thanks for your great plugin.
Is it possible to write numbers in cells and have the sheet treat them as numeric?
Every number I write in a cell results in an alphanumeric cell.
Stefano

column size

Thanks for your hard work.

is there away to control the column's width manually or make it expand to the size of the longest row?

Password Protection

Password protection seems to be planned for a next release.

When will it be available ?

Because every version of flutter_test from sdk depends on xml 3.7.0 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4. So, because exceltest depends on both excel ^1.0.9 and flutter_test any from sdk, version solving failed. pub get failed (1; So, because exceltest depends on both excel ^1.0.9 and flutter_test any from sdk, version solving failed.)

Hello. I did what you said in the issues #11 (flutter update-packages --force-upgrade) but I still have the same issue. I cannot use excel 1.09 (I can only use excel 1.03)
my flutter -doctor

/home/jorge/flutter/bin/flutter doctor --verbose
[✓] Flutter (Channel beta, v1.17.0, on Linux, locale en_US.UTF-8)
• Flutter version 1.17.0 at /home/jorge/flutter
• Framework revision e6b34c2b5c (6 weeks ago), 2020-05-02 11:39:18 -0700
• Engine revision 540786dd51
• Dart version 2.8.1

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /home/jorge/Android/Sdk
• Platform android-29, build-tools 29.0.3
• Java binary at: /snap/android-studio/90/android-studio/jre/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.

[✓] Chrome - develop for the web
• Chrome at google-chrome

[✓] Android Studio (version 3.6)
• Android Studio at /snap/android-studio/88/android-studio
• Flutter plugin version 45.1.1
• Dart plugin version 192.8052
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] Android Studio (version 4.0)
• Android Studio at /snap/android-studio/90/android-studio
• Flutter plugin version 45.1.2
• Dart plugin version 193.7361
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

Dependency Issue

I tried to install the latest version of excel and got this error:

Because every version of flutter_test from sdk depends on xml 3.6.1 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4.
So, because flutter_excel_test depends on both excel ^1.1.0 and flutter_test any from sdk, version solving failed.
pub get failed (1; So, because flutter_excel_test depends on both excel ^1.1.0 and flutter_test any from sdk, version solving failed.)

I'm using Flutter V 1.17.5. Any ideas on how to fix this?

Speed

I have a data set of approximately 6000 records by 20 columns. When executing the code below, the sheet.appendRow(row) seems to take extremely long. If I remove the append it executes in less than a second, if I add it back in it takes 2+ minutes to complete. Am I missing a step or is there an easier (faster) means of importing an entire set of data into excel?

Example (sheet is the default) :

    List<String> row = List<String>();
    i++;
    print(i.toString());
    columns.forEach((column)
    {
      if (map.containsKey(column))
            row.add(map[column].toString());
      else row.add('');
    });
    sheet.appendRow(row);

Not compatible with flutter_test

If I include excel in my project I get the following dependency error:

[MyApp] flutter pub get
Running "flutter pub get" in MyApp...
Because every version of flutter_test from sdk depends on xml 3.6.1 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4.
So, because Herein depends on both excel ^1.0.8 and flutter_test any from sdk, version solving failed.

pub get failed (1; So, because MyApp depends on both excel ^1.0.8 and flutter_test any from sdk, version solving failed.)
exit code 1

What should I do? I need both: tests and excel.

Error in excel when open the file

Hello. I am creating an excel file using your library as follow:

var excel = Excel.createExcel();
var sheet = excel[AppStrings.excelSheetName];
excel.setDefaultSheet(AppStrings.excelSheetName);

CellStyle cellStyle = CellStyle(
    backgroundColorHex: "#F44336",
    fontColorHex: "#FFFFFF",
    bold: true,
    verticalAlign: VerticalAlign.Top);

//Create the title of the fields for each column
for (int index = 0; index < _questionsName.length; index++) {
  var cell = sheet
      .cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: index));
  cell.cellStyle = cellStyle;
  cell.value = _questionsName[index];
}

//Write the excel file
String outputFile = "$path/$file";
excel.encode().then((onValue) {
  File(join(outputFile))
    ..createSync(recursive: true)
    ..writeAsBytesSync(onValue);
});

Everything works well... Later on I create a routine to send it by email and I successfully open the file. But the issue comes when I download the file directly from the email, tried to copy one of the sheet to another excel file... it seems excel not recognize the file and crash immediately.

I find a work around that is dowloading the file, saving as with another name and then copy the sheet to another file excel. But this is not what I would like to do. I would like to be able to copy the excel sheet directly from the original file generated.

Black screen while _workbook = await Excel.decodeBytes(_fileContentInBytes);

Hi! I would like your support on this.

The package works fine, however is see a 'black screen' while executing the following code:

Excel _workbook = await Excel.decodeBytes(_fileContentInBytes);

It remains about 3 or 4 seconds while processing the file content, and I believe it is because of the file size.

Is there any possibility to show a 'pop up' and say processing, or present something different than the black screen?

Thanks in advance

Styling

Are you planning on adding various cell styling / text styling?

Reading XLSX file using Viewer

Thanks for this great plugin.
Which plugin do you suggest to read the XLSX file. I am looking to preview XLSX file in my flutter app without losing styles.

Formatting is removed on save

Before:
Screen Shot 2020-06-15 at 1 31 28 PM

After:
Screen Shot 2020-06-15 at 1 31 07 PM

Code:

import 'dart:io';
import 'package:path/path.dart';
import 'package:excel/excel.dart';

final String FILE_NAME = 'Book1.xlsx';
final String SHEET_NAME = 'Sheet1';
final File file = File(join(FILE_NAME));
final Excel excel = Excel.decodeBytes(file.readAsBytesSync());

void main(List<String> args) async {
  save();
}

void save() {
  excel.encode().then((onValue) {
    File(join('output.xlsx'))
    ..writeAsBytesSync(onValue);
  });
}

Attachments:
Book1.xlsx

Environment:
Dart VM version: 2.8.1 (stable) (Thu Apr 30 09:25:21 2020 +0200) on "macos_x64"
Excel package version: 1.0.9
MacOS version: 10.15.5

Read files in Web

Since you need the dart.io package, which is not really supported in flutter for web, I can not find a way to read excel files that are selected in a browser.

I am using this code to get the file:

import dart:html;
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((final Event event) {
    final File file = uploadInput.files.first;
}

change orientation of text

is there a way to change the orientation of the text in a cell? basically just rotating it by 90 or 270 degrees.
click here if you dont know what i mean.

thanks for the good work!

Formula value is not recalculated

Output:

A1: 1
B1: 3
C1: A1 + B1 = 4
A1: 1
B1: 5
C1: A1 + B1 = 4

Code:

import 'dart:io';
import 'package:path/path.dart';
import 'package:excel/excel.dart';

final String FILE_NAME = 'Book2.xlsx';
final String SHEET_NAME = 'Sheet1';
final File file = File(join(FILE_NAME));
final Excel excel = Excel.decodeBytes(file.readAsBytesSync());

void main(List<String> args) async {
  var cell = getData(0, 0);
  var cell2 = getData(1, 0);
  var formulaCell = getData(2, 0);
  print('${cell.cellId}: ${cell.value}');
  print('${cell2.cellId}: ${cell2.value}');
  print('${formulaCell.cellId}: ${formulaCell.value.formula} = ${formulaCell.value.value}');
  setValue(1, 0, 5);
  
  cell = getData(0, 0);
  cell2 = getData(1, 0);
  formulaCell = getData(2, 0);
  print('${cell.cellId}: ${cell.value}');
  print('${cell2.cellId}: ${cell2.value}');
  print('${formulaCell.cellId}: ${formulaCell.value.formula} = ${formulaCell.value.value}');
}

dynamic getData(int col, int row) {
  return excel[SHEET_NAME].row(row)[col];
}

void setValue(int col, int row, dynamic value) {
  excel.updateCell(SHEET_NAME, CellIndex.indexByColumnRow(columnIndex: col, rowIndex: row), value);
}

Attachments:
Book2.xlsx

Environment:
Dart VM version: 2.8.1 (stable) (Thu Apr 30 09:25:21 2020 +0200) on "macos_x64"
Excel package version: 1.0.9
MacOS version: 10.15.5

How I can get each value from cell?

HI
I use this package for import data from excel, and I wanna do operation for each cell in for()
like

for (var row in excel.tables[table].rows) {
     for (var col in excel.tables[table].cols) {
     print("Cell  $cell");
}
}

But there is no this function, so I find this CellIndex.indexByColumnRow(0,0) but it make an error.

I'm not able to save the file

Hello! Followed the documentation, but the file is not being saved to the directory. My code:

return RaisedButton(
      onPressed: ()async{
        final Directory appDocDir = await getApplicationDocumentsDirectory();
        final String finalDocDir = appDocDir.path;

        final Excel excel = Excel.createExcel();
        try {
          excel.encode().then((onValue){
            File(join("$finalDocDir/form.xlsx"))..createSync(recursive: true)
            ..writeAsBytesSync(onValue as List<int>);
          });
        } catch (e) {
          debugPrint(e.toString());
        }
      },
    );

I had to convert to List because the method does not accept List ,
no console error is displayed

Saving an Excel file on Web

I used universal_io as alternative for dart:io
and I used path package to have the join method

  static void initExcel(){
    var excel = Excel.createExcel();
    excel.rename("Sheet1", "Andrew");
    excel.encode().then((onValue) {
      File(join("excel.xlsx"))
        ..createSync(recursive: true)
        ..writeAsBytesSync(onValue);
    });
  }

The following code produces an error. I imagine it's the use of File...
Docs don't currently have any indication on how to save excels for web...

[Question] Empty sheet on Excel creation

Hi,
First of all, thank you very much for this awesome library! It does work perfectly well despite it's not complete yet.

I have some kind of an issue, we could say. Because it's not a bug, just some behaviour i wasn't expecting.

The "issue" is that i create an XLSX just fine, with a custom named sheet. The content gets added just fine by calling the updateCell() method. Everything seems to be fine, until i export it to a file. That file contains the sheet i created, with my custom name. But it also contains another sheet. That sheet is called "Sheet1", and it's the default sheet that displays to the user and also it is empty.

My question is: How can i get rid of that empty sheet "Sheet1"?

Many thanks again!

Affecting formulas after editing

Hi,
I have a base excel sheet with formulas in it, after I edited the sheet and saved it, the formulas were corrupted.
Are you aware about that

Thank you so much for such a great package
Sam,

FileSystemException: Cannot open file, path = 'assets/database.xlsx' (OS Error: No such file or directory, errno = 2)

Hey all,

I'm trying to load an .xlsx file in order to convert its contents into a list.
I've tied to follow the documentation, yet without success, since the file is not recognized even tough (imo) everything is in place.
I've imported many images and other files and everything works well except that...

I've cleand my flutter and all dependencies work just fine.
The file is in place and not corrupt.
The file is referrenced in the assets section of my pubspec.yaml

My trouble code is (second line):
var file = 'assets/database.xlsx'; var bytes = File(file).readAsBytesSync();

Pubspec:
assets: - assets/database.xlsx

The full error message is:
E/flutter ( 9858): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/database.xlsx' (OS Error: No such file or directory, errno = 2) E/flutter ( 9858): #0 _File.throwIfError (dart:io/file_impl.dart:645:7) E/flutter ( 9858): #1 _File.openSync (dart:io/file_impl.dart:489:5) E/flutter ( 9858): #2 _File.readAsBytesSync (dart:io/file_impl.dart:549:18) E/flutter ( 9858): #3 _MyHomePageState.readExcel (package:prophetix/main.dart:106:28) E/flutter ( 9858): #4 _MyHomePageState.searchDB (package:prophetix/main.dart:121:5) E/flutter ( 9858): <asynchronous suspension> E/flutter ( 9858): #5 SearchBarController._search (package:flappy_search_bar/flappy_search_bar.dart:50:17) E/flutter ( 9858): #6 _SearchBarState._onTextChanged.<anonymous closure> (package:flappy_search_bar/flappy_search_bar.dart:295:29) E/flutter ( 9858): #7 _rootRun (dart:async/zone.dart:1122:38) E/flutter ( 9858): #8 _CustomZone.run (dart:async/zone.dart:1023:19) E/flutter ( 9858): #9 _CustomZone.runGuarded (dart:async/zone.dart:925:7) E/flutter ( 9858): #10 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23) E/flutter ( 9858): #11 _rootRun (dart:async/zone.dart:1126:13) E/flutter ( 9858): #12 _CustomZone.run (dart:async/zone.dart:1023:19) E/flutter ( 9858): #13 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23) E/flutter ( 9858): #14 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15) E/flutter ( 9858): #15 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19) E/flutter ( 9858): #16 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5) E/flutter ( 9858): #17 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12) E/flutter ( 9858):

Any help is very appreciated. Thank you for your time!

Doubt about font customization

Hello, first I would like to thank you for the beautiful package.

Is there any provision for introducing:
-Font Family
-Text Size
-Italic
-Underline
-Bold

Is there any way we can help you? This would be an extremely useful feature

[Feature] Add support for Date data type

Hello, how do I receive the fields as Date?
I have a column with the fields as Date but when I order to display some numbers appear.
For example the date in the file is: 08/05/2020 12:00:00
No Flutter in print (as your example) appears: 43959.5
How to solve?

add feature: RTL Sheets

Hi,
would you mind adding RTL (Right to Left) sheet creating support. although when editing existing RTL sheet name I figured out that it becomes LTR, can you fix this.

Reading a cell with sheet.cell() changes the data to null

Pretty strange issue here. This is my code. I'm essentially parsing a table

Test Upload.xlsx

final bytes = File(filePath).readAsBytesSync();
final excel = Excel.decodeBytes(bytes);
final defaultSheet = await excel.getDefaultSheet();
final sheet = excel[defaultSheet];
// Cell B1 is 60 here
final widthCell = sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0));
// But now it is null
print(widthCell.value);

There is code in cell() on line 104 and 105 of sheet.dart that seems to be causing this. It seems that is just isn't carrying the value over. Am I doing something wrong?

No way to insert a row

It's great package, thanks for contribution.
Herein I would like report an issue there is no way to insert a row. Both insertRow and insertRowIterables are failed.

  1. insertRow will cause the sheetObject crash, everything behind the index will be gone.
  2. insertRowIterables will overwrite the index's row. And on the row, the length is double with same length of "null".

Could you please check it? Or if you need a sample code for reproducing issue, I can make it. Please let me know.

Saving files

I have an issue,
I am getting the path using getExternalStorageDirectory
I have a file in an asset directory (as a template), I am reading that file

Future<ex.Excel> loadExcel(
      {@required String sheet, @required String fileName, bool isAsset = false}) async {
    File file = File(fileName);
    ByteData data;
    if (isAsset == true) {
       data = await rootBundle.load(fileName);}
      else { 
        print("arrived to read filename $fileName");
        data = file.readAsBytesSync().buffer.asByteData();
        }
    var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    ex.Excel excel = ex.Excel.decodeBytes(bytes, update: true);
    return excel;
  }

I use rootBundle.load is from the asset and using file if it is from the app directory (through the path)

saving got no issue, using 

Future<void> saveExcelSheet(
      {@required ex.Excel excel, @required String fileName}) async {
    String dir = await getPath();
    if (await Permission.storage.request().isGranted) {
      excel.encode().then((onValue) async {
        File file = File("$dir/$fileName");
          file.createSync(recursive: true);
          file.writeAsBytesSync(onValue);
      });
    } else {
      print('permission not granted');
    }
  }
}

what I am facing, is if I initiate the file (copy it to the app directory) and try to read it immediatly, I get file not found error, even though the file exist

I thought it might be that the file needs to be closed, but I could not figure it out how to close the file.,

Any ideas?

Unable to parse through some excel files

I was trying to parse through the an xls file which gave me the given error, this error has occurred for some xlsx files as well

E/flutter (21854): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Could not find End of Central Directory Record
E/flutter (21854): #0 ZipDirectory._findSignature (package:archive/src/zip/zip_directory.dart:149:5)
E/flutter (21854): #1 new ZipDirectory.read (package:archive/src/zip/zip_directory.dart:28:20)
E/flutter (21854): #2 ZipDecoder.decodeBuffer (package:archive/src/zip_decoder.dart:21:30)
E/flutter (21854): #3 ZipDecoder.decodeBytes (package:archive/src/zip_decoder.dart:15:12)
E/flutter (21854): #4 new Excel.decodeBytes (package:excel/src/excel.dart:122:32)
E/flutter (21854): #5 Excelifiers.excelToSql (package:excelify/Excelifiers.dart:57:23)
E/flutter (21854):
E/flutter (21854): #6 _HomeState.build. (package:excelify/home.dart:45:35)
E/flutter (21854): #7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (21854): #8 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (21854): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (21854): #10 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (21854): #11 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (21854): #12 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (21854): #13 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (21854): #14 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (21854): #15 PointerRouter._dispatchEventToRoutes. (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (21854): #16 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (21854): #17 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (21854): #18 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (21854): #19 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (21854): #20 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (21854): #21 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (21854): #22 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (21854): #23 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (21854): #24 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (21854): #25 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (21854): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (21854): #27 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (21854): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)

Cannot update to versions past 1.0.3

Getting version 1.0.9 gives me this error:

Because every version of flutter_test from sdk depends on xml 3.6.1 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4.
So, because application depends on both excel ^1.0.9 and flutter_test any from sdk, version solving failed.
pub get failed (1; So, because application depends on both excel ^1.0.9 and flutter_test any from sdk, version solving failed.)

Create Multiple Sheets

Is it possible to create a multiple sheets, example MySheet1, MySheet2, MySheet3. . . . ?

Change size of a cell

hey @justkawal, is it possible to change the size of a single cell?
So basically changing the width of a specific column and the height of a specific row.

Because every version of flutter_test from sdk depends on xml 3.5.0 and excel >=1.0.4 depends on xml ^4.1.0

I have tried to use excel 1.0.4
I can't advance by this error..
Please, help me. Thank you.
"Because every version of flutter_test from sdk depends on xml 3.5.0 and excel >=1.0.4 depends on xml ^4.1.0, flutter_test from sdk is incompatible with excel >=1.0.4.

So, because flutter_app_sheet depends on both excel ^1.0.4 and flutter_test any from sdk, version solving failed.
pub get failed (1; So, because flutter_app_sheet depends on both excel ^1.0.4 and flutter_test any from sdk, version solving failed.)"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.