Flutter 导出excel文件

一、引入flutter插件

dependencies:
  syncfusion_flutter_xlsio: ^20.3.50-beta
  dio: ^4.0.6
  open_file: ^3.2.1

二、在utils中创建helper文件夹

三、在helper中创建save_file_mobile.dart和save_file_web.dart文件

///save_file_mobile
import 'dart:io';
import 'package:open_file/open_file.dart' as open_file;
import 'package:path_provider/path_provider.dart' as path_provider;
// ignore: depend_on_referenced_packages
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';

///To save the Excel file in the device
///To save the Excel file in the device
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
  //Get the storage folder location using path_provider package.
  String? path;
  if (Platform.isAndroid ||
      Platform.isIOS ||
      Platform.isLinux ||
      Platform.isWindows) {
    final Directory directory =
        await path_provider.getApplicationSupportDirectory();
    path = directory.path;
  } else {
    path = await PathProviderPlatform.instance.getApplicationSupportPath();
  }
  final File file =
      File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
  await file.writeAsBytes(bytes, flush: true);
  if (Platform.isAndroid || Platform.isIOS) {
    //Launch the file (used open_file package)
    await open_file.OpenFile.open('$path/$fileName');
  } else if (Platform.isWindows) {
    await Process.run('start', <String>['$path\\$fileName'], runInShell: true);
  } else if (Platform.isMacOS) {
    await Process.run('open', <String>['$path/$fileName'], runInShell: true);
  } else if (Platform.isLinux) {
    await Process.run('xdg-open', <String>['$path/$fileName'],
        runInShell: true);
  }
}
///save_file_web
import 'dart:async';
import 'dart:convert';
// ignore: avoid_web_libraries_in_flutter
import 'dart:html';

///To save the Excel file in the device
///To save the Excel file in the device
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
  AnchorElement(
      href:
          'data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}')
    ..setAttribute('download', fileName)
    ..click();
}

四、在utils中创建excel.dart文件

import 'package:syncfusion_flutter_xlsio/xlsio.dart' as Flutter_xlsio;
import 'helper/save_file_mobile.dart'
    if (dart.library.html) 'helper/save_file_web.dart';

class Excel {
  static Future<void> generateExcel(
    // Excel标题
    List<String>? columnList,
    // Excel数据
    List? dataList,
    // Excel文件名称
    String? excelName,
  ) async {
    List excelHeader = [
      'A1',
      'B1',
      'C1',
      'D1',
      'E1',
      'F1',
      'G1',
      'H1',
      'I1',
      'J1',
      'K1',
      'L1',
      'M1',
      'N1',
      'O1',
      'P1',
      'Q1',
      'R1',
      'S1',
      'T1',
      'U1',
      'V1',
      'W1',
      'X1',
      'Y1',
      'Z1',
    ];
    // 创建一个Excel
    final Flutter_xlsio.Workbook workbook = Flutter_xlsio.Workbook();
    // 通过索引访问工作表第0个sheet.
    final Flutter_xlsio.Worksheet sheet = workbook.worksheets[0];
    // 设置标题
    for (int i = 0; i < columnList!.length; i++) {
      sheet.getRangeByName(excelHeader[i]).columnWidth = 20.00;
      sheet.getRangeByName(excelHeader[i]).setText(columnList[i]);
    }
    // 这里循环取数据
    for (int i = 0; i < dataList!.length; i++) {
      int index = 1;
      dataList[i].entries.forEach((element) {
        sheet.getRangeByIndex(i + 2, index).setText("${element.value}");
        index++;
      });
    }
    List<int> bytes = workbook.saveAsStream();
    workbook.dispose();

    await saveAndLaunchFile(bytes, excelName);
  }
}

五、在其他文件中引入

import 'package:***/utils/excel.dart';



  MaterialButton(

      onPressed: () => Excel.generateExcel(dataList, columnList),
      
      child: Text('导出Excel'),
  )

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要在Flutter应用程序中导出Excel文件并在其中显示图片,你可以使用syncfusion_flutter_xlsio插件。该插件支持将文本和图片写入Excel文件。首先,你需要将在线图片地址转换为Uint8List格式。你可以使用dio库下载图片并将其转换为Uint8List,然后使用syncfusion_flutter_xlsio插件将其写入Excel文件中。以下是一个示例代码: ``` import 'dart:io'; import 'package:image/image.dart' as imgLib; import 'package:dio/dio.dart'; import 'dart:convert'; import 'package:syncfusion_flutter_xlsio/xlsio.dart' as Flutter_xlsio; import 'package:path_provider/path_provider.dart' as path_provider; Future<Uint8List> downloadImage(String imageUrl) async { Dio dio = Dio(); Response response = await dio.get(imageUrl, options: Options(responseType: ResponseType.bytes)); return response.data; } void exportExcelWithImage() async { // 创建一个新的Excel文档 Flutter_xlsio.Workbook workbook = Flutter_xlsio.Workbook(); Flutter_xlsio.Worksheet sheet = workbook.worksheets[0]; // 下载并转换图片 Uint8List imageBytes = await downloadImage('https://example.com/image.jpg'); imgLib.Image image = imgLib.decodeImage(imageBytes); imgLib.Image resizedImage = imgLib.copyResize(image, width: 100, height: 100); Uint8List resizedImageBytes = imgLib.encodeJpg(resizedImage); // 将图片插入Excel文件 sheet.insertImage(1, 1, resizedImageBytes); // 保存Excel文件 String filePath = (await path_provider.getTemporaryDirectory()).path + '/exported_excel.xlsx'; await workbook.saveAs(filePath); print('Excel文件导出到:$filePath'); } exportExcelWithImage(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值