Last active
November 27, 2021 21:40
-
-
Save franciscojsc/d26a268f37a2d2818389c4f8613daa90 to your computer and use it in GitHub Desktop.
Read file xlsx and convert to script sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const xlsxFile = require('read-excel-file/node'); | |
const fs = require('fs'); | |
(async () => { | |
const xlsx = await xlsxFile('./file.xlsx'); | |
const data = xlsx.slice(1); | |
const nameTable = 'demo.tableX'; | |
save(`INSERT INTO ${nameTable} VALUES \n`); | |
data.forEach((row) => { | |
const values = row | |
.map((value) => { | |
try { | |
var date = new Date(value); | |
return `'${date.toISOString().slice(0, 19).replace('T', ' ')}'`; | |
} catch (error) {} | |
if (typeof value === 'string') { | |
return `'${value}'`; | |
} | |
if (typeof value === 'number') { | |
return value; | |
} | |
if (typeof value === 'boolean') { | |
return value ? 1 : 0; | |
} | |
if (value === null || value === undefined) { | |
return 'NULL'; | |
} | |
return value; | |
}) | |
.join(', '); | |
save(`(${values}),`); | |
save('\n'); | |
}); | |
console.log('Success'); | |
})(); | |
function save(content) { | |
fs.appendFileSync('script.sql', content); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment