我下载了适用于网络的 excel 功能,但代码甚至无法为移动设备编译。
downloadExcelFile() async {
// Convert the Excel data to bytes
final excelBytes = excel.encode();
if (kIsWeb == true) {
// Serve the file as a download (web implementation)
final blob = html.Blob([excelBytes],
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
final url = html.Url.createObjectUrl(blob);
final anchorElement = html.AnchorElement(href: url)
..setAttribute('download', 'Job_Data_Export.xlsx')
..click();
// Clean up and release the object URL
await Future.delayed(Duration(seconds: 1));
anchorElement.remove();
html.Url.revokeObjectUrl(url);
} else {
// Write the data to a file (mobile implementation)
final file = File('Job_Data_Export.xlsx');
await file.writeAsBytes(excelBytes!);
// Share the file on mobile
final filePath = file.path;
await share.Share.file(
'Job Data Export',
'Job_Data_Export.xlsx',
excelBytes,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
text: 'Check out the exported job data.',
);
}
}
它抛出:
: Error: Method not found: 'Blob'.
job_list_controller.dart:253
final blob = html.Blob([excelBytes],
^^^^
: Error: Undefined name 'Url'.
job_list_controller.dart:255
final url = html.Url.createObjectUrl(blob);
^^^
: Error: Method not found: 'AnchorElement'.
job_list_controller.dart:257
final anchorElement = html.AnchorElement(href: url)
要解决此问题,您可以使用 share.Share 类。
import 'package:share/share.dart';
void downloadExcelFile() async {
// Convert the Excel data to bytes
final excelBytes = excel.encode();
// Write the data to a file (mobile implementation)
final file = File('Job_Data_Export.xlsx');
await file.writeAsBytes(excelBytes!);
// Share the file on mobile
final filePath = file.path;
await Share.shareFiles([filePath],
text: 'Please Check exported data.',);
}
此代码将共享文件Job_Data_Export.xlsx