使用javascript保留csv文件中的前导零 [英] Preserve leading zero in csv file using javascript

查看:59
本文介绍了使用javascript保留csv文件中的前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码下载csv.

I am downloading a csv using the following code.

<a download="somedata.csv"  id='x'>Download CSV</a>
<script>
       var csv = '01'; //prints 1 in the cell, truncating leading zero
       var csv = "'"+01+"'"; //prints '01' in the cell, with single quote
       var csv = '"\""01"\""'; //prints "01" in the cell, with double quotes
       var a = document.getElementById('x');
       a.href='data:text/csv;base64,' + btoa(csv);
</script>

我需要在csv文件中打印带有前导零的数字.到目前为止,我发现的解决方案是通过将数字用单引号或双引号引起来使数字成为文本.但这并不能解决问题,因为它还在单元格中打印了引号.

I need to print the numbers with leading zeroes in the csv file. The solution I have found so far is to make the number a text by wrapping it either with single or double quotes. But this does not solve the problem as it prints the quotes also in the cell.

是否没有办法保留前导零并在单元格中打印不带引号的数字?有什么建议吗?

Isn't there a way to preserve the leading zeroes and print the numbers without quotes in the cell? Any suggestions?

我忘了在原始帖子中提到我必须在Excel中打开csv.

I forgot to mention in the original post that I MUST need to open the csv in Excel.

var csv = "'01";   //prints '01 in the cell
var csv = '="01"'; //prints  01 in the cell, but the value is ="01"

没有办法获取单元格值并将其都显示为01(而不是不同的显示和值)吗?

Isn't there a way to get the cell value and display both as 01 (instead of different display and value)?

推荐答案

您的代码实际有效:

<a download="somedata.csv"  id='x'>Download CSV</a>
<script>
       var csv = '01';
       var a = document.getElementById('x');
       a.href='data:text/csv;base64,' + btoa(csv);
</script>

如果您在文本编辑器中打开此文件,则会出现前导零.

If you open this file in a text-editor the leading zero is present.

如果您专门针对Microsoft Excel,则可以添加前导单引号以保留前导零-尽管您仍然需要输入每个单元格并按Enter才能使其生效!:

If you are specifically targeting Microsoft Excel, you can add a leading single-quote to preserve the leading zero - although you'll still need to enter each cell and hit enter to make it take effect!:

<a download="somedata.csv"  id='x'>Download CSV</a>
<script>
       var csv = "'01";
       var a = document.getElementById('x');
       a.href='data:text/csv;base64,' + btoa(csv);
</script>

更令人费解-但是有效(同样仅适用于Excel)

More convoluted - but works (again only for Excel)

<a download="somedata.csv"  id='x'>Download CSV</a>
<script>
       var csv = '="01"';
       var a = document.getElementById('x');
       a.href='data:text/csv;base64,' + btoa(csv);
</script>

这篇关于使用javascript保留csv文件中的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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