1212import { ref , Ref } from ' vue' ;
1313import { callAdminForthApi } from ' @/utils' ;
1414import adminforth from ' @/adminforth' ;
15+ import Papa from ' papaparse' ;
1516
1617const inProgress: Ref <boolean > = ref (false );
1718
@@ -63,32 +64,43 @@ async function importCsv() {
6364 return ;
6465 }
6566
66- // post data in format, plain json
67- // data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
68- const data = {};
6967 const reader = new FileReader ();
7068 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 } ` );
8093 }
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+ });
83101 }
84- await postData (data );
85102 };
86103 reader .readAsText (file );
87-
88-
89-
90104 };
91-
92105}
93-
94106 </script >
0 commit comments