【问题标题】:How to format CSV file to display like a table in html如何格式化 CSV 文件以像 html 中的表格一样显示
【发布时间】:2018-02-27 01:09:45
【问题描述】:

我在网上找到了这段代码(感谢所有者,对不起,我忘记了网站),我只是想给它添加样式(我刚开始练习我的 html 并尝试用 csv 格式显示)但它没有显示.我唯一能做的就是添加一些边框并更改文本颜色。

我想要做的是让它以表格格式显示,当它上传时表格行出现。我做了很多研究,但我仍然无法弄清楚。我也尝试使用 Table td 和 tr 但它不起作用,我不确定将它放在代码中的哪个位置。也许我太笨了,所以请原谅我......

<!DOCTYPE html>
<html>  
<head>  

    <script type="text/javascript">

            function loadFile(o)
            {
                var fr = new FileReader();
                fr.onload = function(e)
                    {
                        showDataFile(e, o);
                    };
                fr.readAsText(o.files[0]);
            }

            function showDataFile(e, o)
            {
                document.getElementById("data").innerText = e.target.result;
                document.getElementById("data").style.color="blue";
                //document.getElementById("data").style.borderRight="thick 
 solid #0000FF";
                //document.getElementById("data").style.columnRuleWidth = 
 "thick";
                //document.getElementById("data").style.columnRuleStyle = 
 "solid";

            }
        </script>

 </head>
 <body>
    Select file to read <input type="file" onchange="loadFile(this)">
    <pre id="data"></pre>

 </body>

 </html>

【问题讨论】:

  • 使用解析器,例如:https://www.jqueryscript.net/demo/jQuery-Plugin-To-Generate-A-Table-From-A-CSV-File-CSV-Parser/
  • 您好,先生,感谢您的回答,我希望不要使用解析器。只需根据 html 内容格式化 csv 的显示。这可能吗?

标签: javascript html csv


【解决方案1】:

function loadFile(o)
{
    var fr = new FileReader();
    fr.onload = function(e)
        {
            showDataFile(e, o);
        };
    fr.readAsText(o.files[0]);
}

function showDataFile(e, o)
{ 
  var getCSVData = e.target.result;
  var rows = getCSVData.split("\n");
  var html = '<table border="1">';
  rows.forEach((data, index) => {
    html += "<tr>";
    var value = data.split(",");

    html += "<td>" + value[0] + "</td>";
    html += "<td>" + value[1] + "</td>";
    html += "<td>" + value[2] + "</td>";
    html += "<td>" + value[3] + "</td>";

    html += "</tr>";
  });
  html += '</table>';
  document.getElementById("data").innerHTML = html;
  document.getElementById("data").style.color="blue";
}
table {
  border-collapse: collapse;
}
<!DOCTYPE html>
<html>  
<head>
</head>
<body>
    Select file to read <input type="file" onchange="loadFile(this)">
    <pre id="data"></pre>

 </body>

 </html>

【讨论】:

  • 正是我想要的。太感谢了。嘿伙计,如果可以的话,是否可以描述脚本文件下的每一行的作用?我只想了解该代码的整个流程。我明白了一些但不是全部..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多