Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 创建csv文件时对符号进行编码_Javascript_Node.js_Express - Fatal编程技术网

Javascript 创建csv文件时对符号进行编码

Javascript 创建csv文件时对符号进行编码,javascript,node.js,express,Javascript,Node.js,Express,在我的网页中,我可以将数据导出到csv文件中,我们可以在Excel中打开和读取该文件。但是我注意到像ô或Ø这样的符号都不受支持。例如,我没有使用Ø,而是使用Ã! 我想阻止这件事,但目前我做不到 app.js: app.post("/exportLibelles", function(req, res) { try { dao.exportLibelle().then((value) => { res.attachment

在我的网页中,我可以将数据导出到csv文件中,我们可以在Excel中打开和读取该文件。但是我注意到像
ô
Ø
这样的符号都不受支持。例如,我没有使用
Ø
,而是使用
Ã!

我想阻止这件事,但目前我做不到

app.js:

app.post("/exportLibelles", function(req, res) {
    try {
        dao.exportLibelle().then((value) =>  {
            res.attachment(__dirname+'/ExportLibelle.csv');
            res.status(200).send(value);
        })

    } catch (e) {
        console.log(e);
    }
})

exportLibelle函数:

async exportLibelle() {
  try {
    let request = "SELECT * FROM PROFACE.dbo.ParametresMachines;"

    let results = await sql.query(request);

    return this.convertToCSV(JSON.stringify(results.recordset))

  } catch (e) {
    console.log(e);
  }
}

convertToCSV(objArray) {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  var str = '', header = '';

  for (var i = 0; i < array.length; i++) {
      var line = '';

      for (var index in array[i]) {
          if (i == 0) {
              if (header != '') {
                 header += ';'
              }
              header += index;
          }
          if (line != '') {
            line += ';'
          }
          line += array[i][index];
      }
      str += line + '\r\n';
  }
  return (header + '\r\n' + str);
}

使用此代码,当我打开csv文件时,所有数据都在一行上,带符号的单词看起来像这样
Tampon%20GO%20%C3%98%203.8%20&%2012
而不是
Tampon GOØ3.8&12

最近有一个非常类似的问题,并且能够通过在csv字符串中预先添加utf-8 bom(
\ufeff
)来解决它。只有这样,Excel才能正确地解释它

因此,在您的情况下,请尝试:

convertToCSV(objArray) {
  //...
  return ('\ufeff'+ header + '\r\n' + str); 
}
在控制器中:

dao.exportLibelle().then((value) =>  {
      res.setHeader('Content-disposition', 'attachment; filename=ExportLibelle.csv');
      res.set('Content-Type', 'text/csv');
      res.status(200).send(value);
})

不幸的是,我仍然有相同的符号问题…好吧,这很奇怪。你确定你的数据库中的数据是utf-8编码的吗?我想,我只有在导出数据时才会遇到这个问题。否则,在网页或MSSM中,我可以看到所有符号。嗯,你能再试试吗?撤消对bom表的更改,只需将内容类型设置为:
res.set('content-type','text/csv;charset=windows-1252')抱歉,仍然无法工作。。。
dao.exportLibelle().then((value) =>  {
      res.setHeader('Content-disposition', 'attachment; filename=ExportLibelle.csv');
      res.set('Content-Type', 'text/csv');
      res.status(200).send(value);
})