csv_data.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'dart:io';
  2. import 'package:archive/archive.dart';
  3. import 'package:jiffy/jiffy.dart';
  4. // import 'package:tp5/core/utils.dart';
  5. class CsvData {
  6. static Future<String> extractTextFileFromZip(
  7. String zipPath, String textFileName) async {
  8. // Read the Zip file from disk.
  9. try {
  10. final bytes = File(zipPath).readAsBytesSync();
  11. // Decode the Zip file
  12. final archive = ZipDecoder().decodeBytes(bytes);
  13. // Look for the text file in the archive
  14. for (final file in archive) {
  15. if (file.name == textFileName) {
  16. // Found the text file
  17. if (file.isFile) {
  18. final data = file.content as List<int>;
  19. String content = String.fromCharCodes(data);
  20. return content;
  21. }
  22. }
  23. }
  24. } finally {}
  25. return "";
  26. }
  27. static Jiffy? getLastModified(String zipPath, String textFileName) {
  28. final bytes = File(zipPath).readAsBytesSync();
  29. final archive = ZipDecoder().decodeBytes(bytes);
  30. for (final file in archive) {
  31. if (file.name == textFileName) {
  32. if (file.isFile) {
  33. return Jiffy.parseFromDateTime(
  34. DateTime.fromMicrosecondsSinceEpoch(file.lastModTime));
  35. }
  36. }
  37. }
  38. return null;
  39. }
  40. static List<List<dynamic>> csv2list(String text,
  41. {bool nulling = true, bool quotes = true, bool trim = true}) {
  42. List<List<dynamic>> out = [];
  43. final lines = text.split("\n");
  44. for (var line in lines) {
  45. final cols = line.split(",").map((String? e) {
  46. if (e != null && quotes) {
  47. e = e.replaceAll('"', "");
  48. }
  49. if (e != null && trim) {
  50. e = e.trim();
  51. }
  52. if (nulling) {
  53. e = (e == "") ? null : e;
  54. }
  55. return e;
  56. }).toList();
  57. // print("${out.length}: $cols");
  58. if (cols.isNotEmpty && cols.length > 1) out.add(cols);
  59. }
  60. return out;
  61. }
  62. // Usage
  63. void main() {
  64. extractTextFileFromZip('path/to/your/zipfile.zip', 'your_text_file.txt');
  65. }
  66. }