Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

javascript导出excel或者csv如何让单元格内容换行?

尝试过使用n,效果变成整行换行了,如何让某个单元格里的内容换行?

<html>
<head>
  <p style="font-size: 20px;color: red;">使用a标签方式将json导出csv文件</p>
  <button onclick='tableToExcel()'>导出</button>
</head>
<body>
  <script>
            
    function tableToExcel(){
      //要导出的json数据
      const jsonData = [
        {
          name:'路人甲',
          phone:'123456789',
          email:'[email protected]'
        },
        {
          name:'炮灰乙',
          phone:'123456789',
          email:'[email protected]'
        },
        {
          name:'土匪丙',
          phone:'1234(char)10 56789',
          email:'[email protected]'
        },
        {
          name:'流氓丁',
          phone:'123456789',
          email:'[email protected]'
        },
      ]
      //列标题,逗号隔开,每一个逗号就是隔开一个单元格
      let str = `姓名,电话,邮箱
`;
      //增加为了不让表格显示科学计数法或者其他格式
      for(let i = 0 ; i < jsonData.length ; i++ ){
        for(let item in jsonData[i]){
            str+=`${jsonData[i][item] + ''},`;     
        }
        str+='
';
      }
      //encodeURIComponent解决中文乱码
      let uri = 'data:text/csv;charset=utf-8,ufeff' + encodeURIComponent(str);
      //通过创建a标签实现
      let link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download =  "json数据表.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
 
</script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

按照csv规范 单元格换行需要把内容用双引号引起来
例如

1,"22
33"
1,2

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...