Flutter web - 如何将 Excel 文件保存到设备

3
我在保存数据到设备时遇到了问题。 我有一个base64字符串,需要将其保存为Excel文件到设备上。 所有操作都在Web上进行。 到目前为止,我发现的所有解决方案都是移动端的,不能满足需求。
请帮忙看看这段代码。它可以保存文件,但是之后我无法打开文件,因此应该是在转换过程中出了问题。由于此解决方案会写入文件,我猜测我可能在进行某些错误的转换。
    //base64StringFile is the file I'm getting from the web. It's a String
    Uint8List bytes = base64.decode(base64StringFile);
    File file = File.fromRawPath(bytes);

    final blob = html.Blob([file]);
    final url = html.Url.createObjectUrlFromBlob(blob);
    final anchor = html.document.createElement('a') as html.AnchorElement
      ..href = url
      ..style.display = 'none'
      ..download = 'myFileName';
    html.document.body.children.add(anchor);

    anchor.click();

    html.document.body.children.remove(anchor);
    html.Url.revokeObjectUrl(url);
2个回答

3

File.fromRawPath 将给定的字节解释为与文件系统相关的路径信息 - 这在这里不相关。

相反,可以直接使用这些字节创建blob,不要使用File对象。

请注意,字节列表被包含在另一个列表中。

此外,在这样做时应指定Excel MIME类型

final blob = html.Blob([bytes], 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

1
   //Method 2:
  import 'package:universal_html/html.dart' as html1;
   //Method 1: 
  import 'package:url_launcher/url_launcher.dart';

     
    exportExcelForWeb(String base64) {
    //Method 1: 
      // launch("data:application/octet-stream;base64,${base64}");
    
    //Method 2:
    
      final anchor = html1.AnchorElement(href: 'data:application/octet-stream;base64,$base64')..target = 'blank';
      // add the name
      anchor.download = 'Export_file.xlsx';
      // trigger download
      html1.document.body.append(anchor);
      anchor.click();
      anchor.remove();
    }

2
虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题,将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释,并指出适用的限制和假设。 - John Conde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接