Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Last active November 27, 2021 21:40
Show Gist options
  • Save franciscojsc/d26a268f37a2d2818389c4f8613daa90 to your computer and use it in GitHub Desktop.
Save franciscojsc/d26a268f37a2d2818389c4f8613daa90 to your computer and use it in GitHub Desktop.
Read file xlsx and convert to script sql
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