I’m trying to add a header row to a CSV file using excel.js, but all the columns in the row are ending up in a single cell.
How can I separate the columns?
Any help will be appreciated
The code I tried is:
static async tratarPlanilha(planilhaPath) {
const workbook = new excelJs.Workbook();
await workbook.csv.readFile(planilhaPath);
const header = ['disciplina teste', 'RESP_1', 'RESP_2', 'RESP_3', 'RESP_4', 'RESP_5', 'MEDIA', 'COD QUESTAO', 'TITULO', 'MEDIA GERAL', 'NUMERO PREENCHIMENTO']
const planilhas = [];
workbook.eachSheet((sheet, sheetId) => {
sheet.eachRow((row, rowNumber) => {
const disciplina = row.getCell(1).value;
const valores = disciplina.split(';');
console.log(valores[0]);
if (!planilhas[valores[0]]) {
planilhas[valores[0]] = new excelJs.Workbook();
planilhas[valores[0]].addWorksheet(sheet.name);
planilhas[valores[0]].getWorksheet(sheet.name).addRow(header);
}
planilhas[valores[0]].getWorksheet(sheet.name).addRow(row.values);
})
});
for (const disciplina in planilhas) {
const outputPath = `planilha_${disciplina[0]}.csv`;
await planilhas[disciplina].csv.writeFile(outputPath);
}
}
4
Answers
Looks like you are placing the header as a row. By looking at the docs, it says that to add a header you can include an extra parameter initializing the csv.
They appear to be in a single cell, because that’s the way Excel on your computer displays CSV on opening it, but if you import it instead, and use
,
as a delimiter, it should display separated.It seems that it separates the data by
;
delimiter, so if it’s not important, you could adapt the CSV delimiter to the way Excel initially displays the data, but that’s not recommended (on some other computer, it might show in a single cell, and it would be harder to process it, because it wouldn’t have comma as a usual separator…).To do that, use
;
as delimiter inoptions
, which you pass towriteFile
Note: this will make
;
as CSV delimiter, not comma (,
)the problem may be in the program to see .csv, I run your code and the output is very good. I am using a vs code extension.
output using vs code excel viewer
Demo code, it will support multiple sheet too.
Save as ‘save-csv.js’
Input file
Result