1
0

csv_data.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(file.lastModDateTime);
  34. }
  35. }
  36. }
  37. return null;
  38. }
  39. static List<List<dynamic>> csv2list(String text,
  40. {bool nulling = true, bool quotes = true, bool trim = true}) {
  41. List<List<dynamic>> out = [];
  42. final lines = text.split("\n");
  43. for (var line in lines) {
  44. final cols = line.split(",").map((String? e) {
  45. if (e != null && quotes) {
  46. e = e.replaceAll('"', "");
  47. }
  48. if (e != null && trim) {
  49. e = e.trim();
  50. }
  51. if (nulling) {
  52. e = (e == "") ? null : e;
  53. }
  54. return e;
  55. }).toList();
  56. // print("${out.length}: $cols");
  57. if (cols.isNotEmpty && cols.length > 1) out.add(cols);
  58. }
  59. return out;
  60. }
  61. // Usage
  62. void main() {
  63. extractTextFileFromZip('path/to/your/zipfile.zip', 'your_text_file.txt');
  64. }
  65. }