如何直接打开HTML或JavaScript格式的CSV文件?[duplicate]

s2j5cfk0  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(260)
    • 此问题在此处已有答案**:

(13个答案)
21分钟前就关门了。
我正在用一个小iframe做一个网站。这个iframe的内容会随着我在其他地方的选择而改变。但是可能会有多达50个小的html页面要打开。我想把这些页面的数据放在一个csv文件中,所以我只需要更新csv,而不是所有的页面。在csv中有一个标题,一个文本,一个图片链接和一个标题。
它工作了。但是我已经知道这个csv文件的位置了。我不需要一个filepicker。有没有一个简单的方法告诉脚本在哪里可以找到这个csv文件?
我试着将文件名放入reader. readAsText公式中(reader. readAsText("ventilatie.csv"),但它一直给我错误。这不会很难,对吧?
csv如下所示(荷兰语):

我的html页面的代码是:

<table>
        <tr>
        <td><h2 id="koptekst"></h2></td>
        <td><button onclick="history.back()" style="float:right">Terug</button></td>
        </tr>
        <tr>
            <td><p id="uitleg"></p></td>
            <td><p><img id="plaatje" style="width:180px"></p>
            <p id="bijschrift"></p></td>
        </tr>
    </table>
    
    <script>
        window.onload = () => {
            let reader = new FileReader(),
                picker = document.getElementById("picker");
            
            picker.onchange = () => reader.readAsText(picker.files[0]);
            reader.onloadend = () => {
                let csv = reader.result;
                
                let rows = csv.split("\r\n");
                let row = rows[3].split(";");
                document.getElementById("koptekst").innerHTML = row[1];
                document.getElementById("uitleg").innerHTML = row[2];
                document.getElementById("plaatje").src = row[3];
                document.getElementById("bijschrift").innerHTML = row[4];
            }
        }
    </script>
</body>
brqmpdu1

brqmpdu11#

可以使用API读取文件,使用回调函数解析和处理csv数据。

window.onload=()=>{
    const callback=(r)=>{
        let rows=r.split('\r\n');
            rows.forEach( ( row, index )=>{
            if( index > 0 ){
                let [ id, title, oms, pla, bij ] =row.split(';');
                console.log( id, title, oms, pla, bij );
            }
        })
    };
    fetch('ventilatie.csv')
        .then(r=>r.text())
        .then(callback)
        .catch(alert)
};
9jyewag0

9jyewag02#

你也许想看看这个:

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}

// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
    // Generate download of hello.txt file with some content
    var text = document.getElementById("text-val").value;
    var filename = "hello.txt";
    
    download(filename, text);
}, false);

https://jsfiddle.net/ourcodeworld/rce6nn3z/2/
来源:https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

w7t8yxp5

w7t8yxp53#

这是我的版本。你可以把文件输入换成获取

// https://stackoverflow.com/a/14991797/295783
const parseCsv = str => { let arr = [], quote = false; for (let row = 0, col = 0, c = 0; c < str.length; c++) { let cc = str[c], nc = str[c + 1]; arr[row] = arr[row] || []; arr[row][col] = arr[row][col] || ''; if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; } if (cc == '"') { quote = !quote; continue; } if (cc == ';' && !quote) { ++col; continue; } if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; } if (cc == '\n' && !quote) { ++row; col = 0; continue; } if (cc == '\r' && !quote) { ++row; col = 0; continue; } arr[row][col] += cc.trim(); } return arr; };

const format = csv => {
//  let rows = parseCsv(csv); // remove the comment
  let rows = parseCsv(testCsv); // delete the line
  const headerRow = rows.splice(0,1).flat();
  const [cell0,cell1,cell2,cell3,cell4] = headerRow; // seems not to be of use

  document.getElementById("tb").innerHTML = rows.map(row => `<tr>
      <td>
        <h2 id="koptekst">${row[1]}</h2>
      </td>
      <td><button onclick="history.back()" style="float:right">Terug</button></td>
    </tr>
    <tr>
      <td>
        <p id="uitleg">${row[2]}</p>
      </td>
      <td>
        <p><img id="plaatje" src="${row[3]}" style="width:180px"></p>
        <p id="bijschrift">${row[4]}</p>
      </td></tr>`).join('');

};

window.addEventListener("DOMContentLoaded", () => {
  // or fetch
  const fileInput = document.getElementById("picker");
  fileInput.addEventListener("change", () => {
    const [file] = fileInput.files;
    if (file) {
      const reader = new FileReader();
      reader.addEventListener("load", format)
      reader.readAsText(file);
    }
  })
})
<input type="file" id="picker" />
<table>
  <thead id="th"></thead>
  <tbody id="tb"></tbody>
</table>

<script>
// test data

const testCsv = `Nr; Titel; Omschrijving; Plaatje; Bijschrift
1.; Ventilatierooster; uitleg 1; plaatje 1;bijschrift 1
2.; Toevoerrooster; uitleg 2; plaatje 2;bijschrift 2
3.; Overstroomvoorziening; uitleg 3; Deurrooster.jpg; Deurrooster
4.; Afvoerrooster; uitleg 4;plaatje 4;bijschrift 4
5.; Ventilatiekanaal; uitleg 5;plaatje 5;bijschrift 5
6.; Toevoerventilator; uitleg 6;plaatje 6;bijschrift 6
7.; Afvoerventilator;uitleg 7;plaatje 7;bijschrift 7
8.; Balansventilatie-unit; uitleg 8;plaatje 8;bijschrift 8`
</script>

相关问题