【问题标题】:export datas to csv using javascript to get a product sheet使用 javascript 将数据导出到 csv 以获取产品表
【发布时间】:2021-07-30 08:33:15
【问题描述】:

我正在使用 Javascript 编写一个程序,该程序可以将数据提取到 csv 文件中。到目前为止,我所做的是创建一个空白文本区域,我们可以在其中粘贴文本,然后程序查找目标公共值并将结果打印到 csv 文件中。更具体地说,这些值对应于产品的特征,我还针对粘贴文本中建立的每个特征的下一个值,以提取特征及其结果。我的目标是通过简单的复制/粘贴将功能产品的所有详细信息放入 csv 文件中,而不是每次都编写。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <textarea id="toConvert" name="" id="" cols="30" rows="10"></textarea>
    <br>
    <button id="submit">Dowload CSV</button>
    
    <script>
        let textArea = document.getElementById('toConvert');
        let btn = document.getElementById('submit');

        btn.addEventListener('click', function(e){
            e.preventDefault();

            let stack = [];

            // features product
            var features = [
                "Matière", 
                "Hauteur",
                "Longueur",
                "Diamètre",
                "Profondeur",
                "Poids",
                "Couleur"
            ]

            textArea.select();
            document.execCommand("copy");
            let result = textArea.value;
            let isFounded = features.filter( item => result.includes(item) );
            let values = result.split(' ');
            for(let i = 0; i < values.length; i++){
                for(let j=0; j < isFounded.length; j++){
                    if(values[i] === isFounded[j]){
                        let rows = [
                            [isFounded[j], values[i+1]]
                        ];
                        
                        rows.forEach(function(rowArray){
                            let row = rowArray.join(',');
                            stack.push(row);
                        });
                        
                        var csvString = stack.join("\r\n");
                        var universalBOM    = "\uFEFF";
                        var a               = document.createElement('a');
                        a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(universalBOM+csvString));
                        a.target            = '_blank';
                        a.download          = 'ficheProduit.csv';
                        document.body.appendChild(a);
                        a.click(); 
                        
                    }
                }
            }
        }, { once: true });
 
    </script>
</body>
</html>


我遇到的问题如下:

  • 该程序仅在粘贴的文本看起来像“Matière Métal Poids 300 Dimensions 500”并且单词之间没有换行符时才有效。我一直在寻找一个正则表达式来替换特殊字符,但我在我的程序中找不到如何做到这一点。
  • 我只是成功地用“,”将功能与其结果分开,它给了我这个:
Matière, Métal
Poids,300

但是我怎样才能在 csv 文件中创建包含两列而不是只有一列的行。 我期望这个输出:

Matière | Métal
Poids   | 300 ..

我很想得到一些帮助,提前谢谢你!!!

【问题讨论】:

    标签: javascript arrays regex loops export-to-csv


    【解决方案1】:

    当我运行您的代码时,我只能获得 csv 文件中的第一项。所以,我更新了提取值的代码。

    用于创建具有相等空格和“|”的 csv 文件字符,到目前为止,我在 javascript 中没有看到任何库。因此,我使用的方法是从“结果”中找到“特征”单词的最大长度,并将空格添加到每个单词中,使长度等于 max_length + 1。

    例如,如果“Matière”的 max_length 为 7,我们会将 csv 中的每个第一个单词的长度设为 8,其余长度与 csv 相加。

    希望这是你想要的:)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    
        <textarea id="toConvert" name="" id="" cols="30" rows="10"></textarea>
        <br>
        <button id="submit">Dowload CSV</button>
        
        <script>
            let textArea = document.getElementById('toConvert');
            let btn = document.getElementById('submit');
    
            btn.addEventListener('click', function(e){
                e.preventDefault();
    
                let stack = [];
    
                // features product
                var features = [
                    "Matière", 
                    "Hauteur",
                    "Longueur",
                    "Diamètre",
                    "Profondeur",
                    "Poids",
                    "Couleur"
                ]
    
                textArea.select();
                document.execCommand("copy");
                let result = textArea.value;
                // ----------
                result = result.split(' ')
    
                // make the result list into boolean list as the item will be true if the word is included in the features
                condition_list = result.map(item => features.includes(item))
    
                // find the maximum length of feature word from result and add + 1 for extra space before "|" in max_length word
                max_length = features.filter( item => result.includes(item) ) // first filter the features words from result
                                    .reduce((acc, cur) => { // reduce the list into one maximum length element
                                        if (cur.length > acc.length) { 
                                            return cur
                                        } else {
                                            return acc
                                        }
                                    }, " ").length + 1
    
                // get pair of feature word from result
                var new_result = []
                let current_list = []
                result.forEach((item, index) => {
                    if(condition_list[index]){ // if it's feature word, we will capture in new list called current_list
                        current_list = []
                        current_list.push(item)
                    }else if(condition_list[index - 1]){ // if it's next value of feature word, we will append to current_list and push it to new_result
                        current_list.push(item)
                        new_result.push(current_list)
                    }
                })
                
                // convert to csv
                let csvContent = "data:text/csv;charset=utf-8,";
                new_result.forEach(row => {
                    let row_with_spaces = ""
                    row.forEach((item, index) => {
                        
                        if (index) { //index === 1 is second item
                            row_with_spaces += " " + item // if it's second item, just append one space before the item
                        } else{
                            row_with_spaces += item + " ".repeat(max_length - item.length) + "|" // if it's first item, fill remaining length with spaces and "|"
                        }
                    })
                    csvContent += row_with_spaces + "\r\n"; 
                });
    
                // download as csv
                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "ficheProduit11.csv");
                document.body.appendChild(link);
    
                link.click()
            }, { once: true });
     
        </script>
    </body>
    </html>
    

    输入:“Matière Métal Poids 300 Dimensions 500”

    输出:

    Matière | Métal
    Poids   | 300
    

    输入:“Matière Métal Poids 300 Diamètre 500”

    输出:

    Matière  | Métal
    Poids    | 300
    Diamètre | 500
    

    【讨论】:

    • 非常感谢它有效!我还创建了另一个代码来显示所有值,但你的可能更好。但我意识到我的问题并不清楚。我的意思是代替“|”在 csv 文件(表格)的另一个单元格中显示,而不是符号。你知道我该怎么做吗?
    • 很高兴听到它有效:) 我对你想要显示的内容感到很困惑。通常,csv 应该只用逗号或分号分隔。因此,当您将其导入另一个程序时,它可以正确解码所有信息。我以为您只想将 csv 用于演示目的。你能告诉我更多关于你对分隔符的期望吗?
    • 如果这解决了问题,请选中复选框以接受它作为答案:) 谢谢!
    • 感谢您的回答!!好的,我现在明白了,对不起我的问题..
    猜你喜欢
    • 2023-02-16
    • 2013-04-09
    • 2011-03-28
    • 1970-01-01
    • 2020-08-03
    • 2012-07-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多