如何使用javascript编写csv文件?

时间:2014-03-21 05:24:28

标签: javascript

我正在动态创建一个数组。以下数组就是一个例子。

textarray = [["label first","details of label 1"],["label sec","details of label 2"],["label 3","details of label 3"],["label 4","details of label 4 and 3"],["label 5","details of label 5"],["label 6","details of label 6"],["label 7","details of label 7"],["label 8","details of label 8"],["label 9","details of label 9"]]

我的最终目标是点击保存按钮阵列将生成,它应该要求我以 EXCEL格式保存/打开。所以我写了这样的东西,

var a = document.createElement('a');
a.href     = 'data:attachment/csv;charset=utf-8,' +textarray;
a.target   = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();

我收到提示保存或打开csv文件,但如果我打开该文件,内容不符合预期(未正确显示)

就是这样,

            **column1**   **column2**   ...........
**row1**    labelfirst  detailsoflabel1  labelsec  detailsoflabel2

一行应该只包含一个元素,如果看到上面的输出,则单词之间没有空格(参见数组)。它应该是这样的,

               **column1**       **column2**

 **row1**      label first    details of label 1

 **row2**      label sec      details of label 2

    .
    .
    .

请帮帮我。

1 个答案:

答案 0 :(得分:0)

**Use this:**
<html>
<script type="text/javascript">
function createCSV() {  
csvRows = [["label first","details of label 1"],["label sec","details of label 2"],["label 3","details of label 3"],["label 4","details of label 4 and 3"],["label 5","details of label 5"],["label 6","details of label 6"],["label 7","details of label 7"],["label 8","details of label 8"],["label 9","details of label 9"]];

    var csvString = csvRows.join("%0A");
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' + csvString;
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();

}
</script>
<body>
    <form action="" method="post">
    <input type="button" value="Create" onclick="createCSV()">
    </form>
</body>
</html>