Flutter中如何通过Uint8List或File使用Syncfusion XLSIO创建Excel工作簿并读取工作表0的数据?
Got it, let's walk through exactly how to get this working with Syncfusion's XLSIO library. First, make sure you've got the right dependency set up, then we'll cover both using the raw Uint8List (from FilePicker) and the File you created.
Step 1: Add Syncfusion XLSIO Dependency
First, add the latest version of syncfusion_flutter_xlsio to your pubspec.yaml:
dependencies: syncfusion_flutter_xlsio: ^25.1.39 # Check for the latest version on pub.dev
Option 1: Use the Raw Uint8List (More Efficient)
You don't even need to convert the Uint8List to a File—Syncfusion's Workbook.open() can take the bytes directly. This saves you from writing to disk, which is better for performance, especially with larger files.
Here's the code:
FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['xlsx'], ); if (result != null) { // Get the raw Uint8List from FilePicker Uint8List excelBytes = result.files.single.bytes!; // Create Workbook from the bytes final Workbook workbook = Workbook.open(excelBytes); // Access the first worksheet (index 0) final Worksheet worksheet = workbook.worksheets[0]; // Example 1: Read a single cell (A1) String? a1Value = worksheet.getRangeByName('A1')?.text; print('Value in A1: $a1Value'); // Example 2: Iterate through all rows/columns in the sheet for (int row = 1; row <= worksheet.lastRow; row++) { for (int col = 1; col <= worksheet.lastColumn; col++) { print('Row $row, Column $col: ${worksheet.getRange(row, col).text}'); } } // Critical: Dispose the workbook to free up memory workbook.dispose(); }
Option 2: Use the File Object
If you already have the File created and want to use that instead, you just need to read the bytes from the file first, then pass them to Workbook.open():
FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['xlsx'], ); if (result != null) { File file = File.fromRawPath(result.files.single.bytes!); // Read bytes from the File Uint8List fileBytes = await file.readAsBytes(); // Create Workbook and access sheet 0 (same as Option 1) final Workbook workbook = Workbook.open(fileBytes); final Worksheet worksheet = workbook.worksheets[0]; // Your data reading logic here... workbook.dispose(); }
Important Notes
- Always call
workbook.dispose()after you're done with it—this prevents memory leaks, which is crucial for Flutter apps. - Syncfusion XLSIO supports both
.xlsxand.xlsformats, so your current allowed extension (xlsx) is fine. - If you're dealing with very large Excel files, consider using streaming or batch processing, but for most use cases, the above approach works perfectly.
内容的提问来源于stack exchange,提问作者berkb

