12
12
import { ref , Ref } from ' vue' ;
13
13
import { callAdminForthApi } from ' @/utils' ;
14
14
import adminforth from ' @/adminforth' ;
15
+ import Papa from ' papaparse' ;
15
16
16
17
const inProgress: Ref <boolean > = ref (false );
17
18
@@ -63,32 +64,43 @@ async function importCsv() {
63
64
return ;
64
65
}
65
66
66
- // post data in format, plain json
67
- // data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
68
- const data = {};
69
67
const reader = new FileReader ();
70
68
reader .onload = async (e ) => {
71
- const text = e .target .result as string ;
72
-
73
- const lines = text .split (' \n ' );
74
- const columns = lines [0 ].split (' ,' );
75
- for (let i = 1 ; i < lines .length ; i ++ ) {
76
- const values = lines [i ].split (' ,' );
77
- for (let j = 0 ; j < columns .length ; j ++ ) {
78
- if (! data [columns [j ]]) {
79
- data [columns [j ]] = [];
69
+ try {
70
+ const text = e .target .result as string ;
71
+
72
+ Papa .parse (text , {
73
+ header: true ,
74
+ skipEmptyLines: true ,
75
+ complete : async (results ) => {
76
+ if (results .errors .length > 0 ) {
77
+ throw new Error (` CSV parsing errors: ${results .errors .map (e => e .message ).join (' , ' )} ` );
78
+ }
79
+ const data: Record <string , string []> = {};
80
+ const rows = results .data as Record <string , string >[];
81
+
82
+ if (rows .length === 0 ) {
83
+ throw new Error (' No data rows found in CSV' );
84
+ }
85
+ Object .keys (rows [0 ]).forEach (column => {
86
+ data [column ] = rows .map (row => row [column ]);
87
+ });
88
+
89
+ await postData (data );
90
+ },
91
+ error : (error ) => {
92
+ throw new Error (` Failed to parse CSV: ${error .message } ` );
80
93
}
81
- data [columns [j ]].push (values [j ]);
82
- }
94
+ });
95
+ } catch (error ) {
96
+ inProgress .value = false ;
97
+ adminforth .alert ({
98
+ message: ` Error processing CSV: ${error .message } ` ,
99
+ variant: ' danger'
100
+ });
83
101
}
84
- await postData (data );
85
102
};
86
103
reader .readAsText (file );
87
-
88
-
89
-
90
104
};
91
-
92
105
}
93
-
94
106
</script >
0 commit comments