You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

69 lines
2.0 KiB

const fs = require('fs')
const path = require('path')
const XLSX = require('xlsx')
const { parse } = require('csv-parse/sync')
const { createMatiere } = require('../Models/Matieres')
const { database } = require('../database')
/**
* Function to import data from the first column of an XLSX or CSV file into SQLite database
* @param {string} filePath - Path to the file (either .xlsx or .csv)
*/
async function importFileToDatabaseMatiere(filePath) {
const fileExtension = path.extname(filePath).toLowerCase()
// Determine the file type and parse accordingly
let records
if (fileExtension === '.xlsx') {
// Read and parse XLSX file
const workbook = XLSX.readFile(filePath)
const worksheet = workbook.Sheets[workbook.SheetNames[0]] // Assuming data is in the first sheet
records = XLSX.utils.sheet_to_json(worksheet, { defval: '' })
} else if (fileExtension === '.csv') {
// Read and parse CSV file
const fileContent = fs.readFileSync(filePath, 'utf8')
records = parse(fileContent, {
columns: true,
skip_empty_lines: true
})
} else {
console.error('Unsupported file format. Only .xlsx and .csv are allowed.')
return
}
try {
let message = ''
let error = true
for (const row of records) {
if (!row.nom || !row.credit || !row.uniter || !row.ue) {
if (!row.nom) {
message = "Le champ 'nom' est inconnu"
} else if (!row.credit) {
message = "Le champ 'credit' est inconnu"
} else if (!row.uniter) {
message = "Le champ 'uniter' est inconnu"
} else if (!row.ue) {
message = "Le champ 'UE' est inconnu"
}
error = false
break
}
}
if (error !== false) {
database.transaction(() => {
for (const row of records) {
createMatiere(row.nom, row.credit, row.uniter, row.ue)
}
})()
}
return { error, message }
} catch (error) {
console.error('Error inserting record:', error)
}
}
module.exports = {
importFileToDatabaseMatiere
}