下面的代码允许我生成一个csv (我在后端的其他地方使用相同的代码,它运行得很好)--在这种情况下,数组中有值,但是当我运行rest调用时,会得到下面的错误,这是什么原因呢?
错误: Errore generazione csv: TypeError:无法将未定义或空转换为对象 nestjs代码:
let obejct2 = {
TotalePreventivi: preventivi,
TotalePreventiviVenduti: preventivivenduti,
DifferenzaEffettuatiVenduti: preventivi - preventivivenduti,
DifferenzaEffettuatiVendutiPercentuale: differenzapercentulaprev,
TotalePreventivato: totalepreventivato,
TotaleVenduto: sommatotalevenduto,
DifferenzaPreventivatoVenduto: totalepreventivato - sommatotalevenduto,
DifferenzaPreventivatoVendutoPercentuale: differenzapreventivatovenduto,
AttivitaPreviste: attivitaprev,
AttivitaConsutivo: attivitaconsu,
DifferenzaAttivitaPrev: attivitaprev - attivitaconsu,
DifferenzaAttivitaPercentuale: diffattivitaperc,
};
console.log(obejct2);
try {
const options = {
fieldSeparator: ",",
quoteStrings: '"',
decimalSeparator: ".",
showLabels: true,
showTitle: true,
title: "Report globale",
useTextFile: false,
useBom: true,
};
const csvExporter = new ExportToCsv(options);
const report = csvExporter.generateCsv(JSON.stringify(obejct2), true);
fs.writeFileSync("dataprevglobale.csv", report);
} catch (err) {
console.log("Errore generazione csv: " + err);
}
return obejct2;
发布于 2021-11-10 06:05:33
我发现您需要在数组中包装对象,并在options变量中设置"useKeysAsHeaders: true“。
// the object needs to be an array, then the lib will get the first object and build the csv file.
let obejct2 = [
{
TotalePreventivi: preventivi,
TotalePreventiviVenduti: preventivivenduti,
DifferenzaEffettuatiVenduti: preventivi - preventivivenduti,
DifferenzaEffettuatiVendutiPercentuale: differenzapercentulaprev,
TotalePreventivato: totalepreventivato,
TotaleVenduto: sommatotalevenduto,
DifferenzaPreventivatoVenduto: totalepreventivato - sommatotalevenduto,
DifferenzaPreventivatoVendutoPercentuale: differenzapreventivatovenduto,
AttivitaPreviste: attivitaprev,
AttivitaConsutivo: attivitaconsu,
DifferenzaAttivitaPrev: attivitaprev - attivitaconsu,
DifferenzaAttivitaPercentuale: diffattivitaperc,
}
];
console.log(obejct2);
try {
const options = {
fieldSeparator: ",",
quoteStrings: '"',
decimalSeparator: ".",
showLabels: true,
showTitle: true,
title: "Report globale",
useTextFile: false,
useBom: true,
useKeysAsHeaders: true,
};
const csvExporter = new ExportToCsv(options);
const report = csvExporter.generateCsv(JSON.stringify(obejct2), true);
fs.writeFileSync("dataprevglobale.csv", report);
} catch (err) {
console.log("Errore generazione csv: " + err);
}
return obeject2;
https://stackoverflow.com/questions/69914274
复制