0% found this document useful (0 votes)
13 views25 pages

AdvMobDev Class01

Uploaded by

saifqutran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

AdvMobDev Class01

Uploaded by

saifqutran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Advance Mobile Application

Development

File management in flutter


1. https://github.com/malkthere/amad-classes-2025/tree/master
2. https://github.com/malkthere/amad-classes-2025/tree/class01-lesson02_Read_excel_file

Dr. Mazin Alkathiri


IT Department
College Of Computers
Seiyun University
2024-2025
Read and write files
In some cases, you need to read and write files to disk. For example,
you might need to persist data across app launches, or download data
from the internet and save it for later offline use.
To save files to disk on mobile or desktop apps, combine the
path_provider plugin with the dart:io library.
This recipe uses the following steps:
• Find the correct local path.
• Create a reference to the file location.
• Write data to the file.
• Read data from the file.
1. What is an Excel File?
Excel files are spreadsheet documents commonly used for
organizing and analyzing data. They are stored in formats such as .xls
or .xlsx, which can contain data in rows and columns, charts, formulas,
and more.
2. Why Use Excel in Mobile Apps?
• Data Management: Excel files can store structured data such as employee
records, sales data, and financial reports.
• Data Analysis: Excel supports calculations and formulas, making it useful for
analytical tasks.
• Portability: Excel files can be shared easily across platforms and applications.
• Business Use Cases: Generating reports, invoices, attendance logs, and exporting
data.
5. Key Features of Excel
Operations
• Dynamic Data Storage: Excel allows dynamic data insertion and
organization.
• Multi-Sheet Support: You can create multiple sheets for separate data
categories.
• Compatibility: Excel files can be easily opened and edited on various
platforms, including mobile and desktop.
Working with Excel Files in
Flutter
• The first thing we need to do is to add excel package to our
pubspecp.yaml file.
excel:
path: syncfusion_flutter_xlsio:
permission_handler:
file_picker:

• And import their packages.


mport 'package:flutter_excel/excel.dart';
mport 'package:permission_handler/permission_handler.dart';
mport 'package:path/path.dart';
Android Permissions:
Add the following permissions to
AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Creates a new Excel workbook

var excel = Excel.createExcel();

•Creates a new Excel workbook using the excel package.

•The Excel.createExcel() method initializes an Excel object with a default sheet named 'Sheet1'.

•The excel object is the main workbook that holds one or more sheets (similar to Excel tabs).

Which will automatically creates 1 empty sheet: Sheet1


• Defines a function named createexcelfile to handle Excel file creation and data entry.

• The async keyword allows the function to handle asynchronous tasks, such as saving files.

void createexcelfile() async{


.
.
.
.
.
}
Inserting data into an excel file

Now that we have an excel file, we can move on to inserting files


into the file. there are two ways of inserting data into an excel file:

1. Getting reference to a single cell in the a sheet

2. Inserting values into a row with List<String>


Getting reference to a single
cell in the a sheet
Sheet sheetObject = excel['01 ‫;]'فاتورة‬
var cell = sheetObject.cell(CellIndex.indexByString("A1"));
cell.value = 8; // dynamic values support provided;

1. Sheet: A sheet is a single page inside of an excel file, if you are familiar with
excel you will understand that a single excel file can contain multiple sheets
1. excel[‘01 ‫]’فاتورة‬: Each sheet in an excel file has a name, so to get reference to the
sheet you need it’s name
2. In the second line of code is used to get reference to cell “A1”, which as we
know is the first cell in the sheet
3. This line sets the value of cell “A1” to 8
Inserting values into a row with
List<String>
Sheet sheetObject = excel['01 ‫;]'فاتورة‬
List<String> data = ["Mr","’mazin", "Alkathiri"];
sheetObject.appendRow(data);

• sheetObject.appendRow(date): This Line of code inserts the List


values into the sheet like this:
createexcelfile()

void createexcelfile() async{


Sheet sheetObject = excel['01 ‫;]'فاتورة‬
var cell = sheetObject.cell(CellIndex.indexByString("A1"));
cell.value = 8; // dynamic values support provided;
List<String> data = ["Mr","’mazin", "Alkathiri"];
sheetObject.appendRow(data);
saveExcel();
}
1. Function Declaration saveExcel()
The function saveExcel() is to save an Excel file in the device's Download
folder. It uses permissions handling and file writing features to ensure proper file
creation and access. Here's a detailed explanation:

saveExcel() async {
.
.
.
.
.
}
2. Requesting Storage Permission
var res = await Permission.storage.request();
•Requests storage permissions from the user at runtime using the permission_handler
package.
•Explanation:
•Permission.storage.request() prompts the user to allow or deny storage access.
•await ensures the function waits for the user's response before continuing.
•Result:
•The res variable stores whether the permission was granted or denied.

•Important Note:
Make sure the permission_handler dependency is added to the pubspec.yaml file:

permission_handler:
3. Saving the Excel Data
var fileBytes =
excel.save();
Saves the current Excel object (excel) to memory as bytes.
These bytes can be written directly to a file.
•excel.save():
•Serializes the Excel workbook into binary data (byte format).
•Returns the file content as Uint8List for writing.
•Example:
Suppose the Excel workbook contains data like this:
Then, fileBytes will contain encoded binary data representing this structure.

A B C
8
Mr Mazin Alkathiri
4. File Path and Creation
File(join("/storage/emulated/0/Download/billNo03.xlsx"))

Specifies the file path and name for the Excel file.
•Path Explanation:
•/storage/emulated/0/Download/:
Refers to the Download folder in the internal storage of an Android device.
•billNo03.xlsx:
The file name. You can change this to suit your needs.
•File Creation:
..createSync(recursive: true)
•Ensures the file is created synchronously if it does not already exist.
•The recursive: true parameter ensures that any missing parent directories are also created.
5. Writing Data to File
..writeAsBytesSync(fileBytes!);

Writes the Excel data (fileBytes) to the newly created file.


•Key Details:
•writeAsBytesSync() writes the bytes synchronously (blocks execution until the process is
complete).
•The ! operator ensures null safety, guaranteeing that fileBytes is not null.
•Output:
•A file named billNo03.xlsx is saved in the Download folder of the device.
•The file contains the data and formatting provided earlier in the Excel object.
Complete Example of Function
saveExcel()
saveExcel() async {
//request for storage permission
var res = await Permission.storage.request();

var fileBytes = excel.save();


File(join("/storage/emulated/0/Download/billNo03.xlsx"))
..createSync(recursive: true)
..writeAsBytesSync(fileBytes!);
}
Function Declaration
void readexcelfile(File? file) async {
.
.
}

Declares a function named readexcelfile that accepts an optional File? parameter named file.
It processes the Excel file to extract and print specific cell values.
•async:
Allows asynchronous operations, although in this code there are no await calls. The function could be
modified to handle asynchronous file operations if needed.
•File?:
The nullable type File? ensures the function can handle cases where the file parameter might be
null.
Reading XLSX File Bytes
var bytes = file!.readAsBytesSync();

• Reads the entire Excel file as bytes (Uint8List) synchronously.

• Details:
•file!: The null-check operator (!) asserts that file is not null at runtime.
•readAsBytesSync(): Reads the file synchronously, blocking
execution until the read operation completes.
Decoding Excel File
var excel = Excel.decodeBytes(bytes);

•Reads the entire Excel file as bytes (Uint8List) synchronously.


•Details:
•file!: The null-check operator (!) asserts that file is not null at runtime.
•readAsBytesSync(): Reads the file synchronously, blocking execution until the read
operation completes.
reading XLSX File

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

for (var row in excel.tables[table]!.rows) {


for (var cell in row) {
print(cell!.value);
}
}
}
void readexcelfile(File? file) async
if(counter>6){
oid readexcelfile(File? file) async { int counter2=0;
var bytes = file!.readAsBytesSync(); for (var cell in row) {
var excel = Excel.decodeBytes(bytes); if(counter==2){ if(counter2==1) {
r (var table in excel.tables.keys) { int counter2=0; if (cell != null)
t counter=0; for (var cell in print(cell!.value);
or (var row in excel.tables[table]!.rows) {row) { }
if(counter==1){ if(counter2==4 if(counter2==2) {
int counter2=0; ){ if (cell != null)
for (var cell in row) { if (cell != null) print(cell!.value);
if(counter2==4) { }
if (cell != null) print(cell!.value); counter2++;
print(cell!.value); } }
} counter2++; }
counter2++; } counter++;
} } }
} }
ElevatedButton(
onPressed: () async {
FilePicker try {
result = await FilePicker.platform.pickFiles();
if (result != null) {
if (!kIsWeb) {
file = File(result!.files.single.path!);
excelobj.readexcelfile(file);
}
} else {
print("user cancled the picker");
}

} catch (_) {}
super.setState(() {
});
},
child: const Text('Pick an Excel File'),
),

You might also like