Node.js生成的csv文件显示英镑为英镑符号(£) [英] Node.js generated csv file is displaying £ for a UK pound sign (£)

查看:158
本文介绍了Node.js生成的csv文件显示英镑为英镑符号(£)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此 json2scv 包解析我的数据(示例json数据在下面的代码中进行了描述)

I'm using this json2scv package parsing my data (sample json data is described in below code)

我正在尝试使用以下代码在nodejs应用程序中生成CSV文件:

I am trying to generate a CSV file in my nodejs application using the code below:

如果我在Excel中打开文件,则在出现£符号的任何地方都会得到£.

If I open the file in Excel, then I get £ wherever a £ sign should appear.

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['car', 'price', 'color'];
var myCars = [
  {
    "car": "Audi",
    "price": "£40000",
    "color": "blue"
  }, {
    "car": "BMW",
    "price": "£35000",
    "color": "black"
  }, {
    "car": "Porsche",
    "price": "£60000",
    "color": "green"
  }
];
var csvStr = json2csv({ data: myCars, fields: fields, del: ',' });

fs.writeFile('file.csv', csvStr, { encoding: 'utf8' },function(err) {
  if (err) throw err;
  console.log('file saved');
});

有什么想法吗?

谢谢.

推荐答案

我从这个答案中得到了解决方案,它是一个问题线程: https://stackoverflow.com/a/27975629/5228251

I have got the solution from this answer and it's question thread: https://stackoverflow.com/a/27975629/5228251

UTF-8示例:

fs.writeFile(someFilename, '\ufeff' + html, { encoding: 'utf8' }, function(err) {
   /* The actual byte order mark written to the file is EF BB BF */
}

UTF-16 Little Endian示例:

fs.writeFile(someFilename, '\ufeff' + html, { encoding: 'utf16le' }, function(err) {
   /* The actual byte order mark written to the file is FF FE */
}

经过上面的答案并且是线程之后,我就修改了我的代码,如下所示:

After go through above answer and it's thread then I have modified my code like this:

  • 将距离计选项更改为"\t"而不是","
  • "\ufeff"添加到csv字符串
  • 更改了编码以使用"utf16le" 代替"utf8"
  • Changed delimeter option to "\t" instead of ","
  • Prepended "\ufeff" to the csv string
  • Changed encoding to use "utf16le" instead of "utf8"

这是我更新的代码:

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['car', 'price', 'color'];
var myCars = [
  {
    "car": "Audi",
    "price": "£40000",
    "color": "blue"
  }, {
    "car": "BMW",
    "price": "£35000",
    "color": "black"
  }, {
    "car": "Porsche",
    "price": "£60000",
    "color": "green"
  }
];
var csvStr = json2csv({ data: myCars, fields: fields, del: '\t' });

fs.writeFile('file.csv', '\ufeff' + csvStr, { encoding: 'utf16le' },function(err) {
  if (err) throw err;
  console.log('file saved');
});

希望这对其他人有帮助.

Hope this helps others.

这篇关于Node.js生成的csv文件显示英镑为英镑符号(£)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆