JavaScript FileReaderを使ってCSVファイルを読み込むサンプル

環境
Windows 10 home 64bit
Google Chrome 107.0.5304.122

構文
1.type fileの要素を取得する
let 変数名 = document.getElementById(“ファイルセレクタID");

2.addEventListenerのイベント登録
変数名.addEventListener('change’, (e) => {
let 変数名 = new FileReader();
ファイルを読み込み
read.readAsText(file);

3.ファイルの内容を表示
read.onload = function(){
要素.textContent = read.result;
}
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>CSVファイルを読み込むサンプル</title>
</head>
<script>
window.onload = function () {
// type型のfileの要素を取得
let tf = document.getElementById("dp");
// 表示用の要素を取得
let objs= document.getElementsByClassName('cft')[0];
tf.addEventListener('change', (e) => {
const target = event.target;
const files = target.files;
const file = files[0];
let read = new FileReader();
// ファイルの内容を表示
read.readAsText(file);
read.onload = function() {
objs.textContent = read.result;
};
read.onerror = function() {
// ファイルの読み込みを失敗する場合
console.log(read.error);
};
});
}
</script>
<body>
<h2>ファイルの内容:<span class="cft"></span></h2>
<form>
<input type="file" id="dp" accept=".csv">
</form>
</body>
</html>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>CSVファイルを読み込むサンプル</title> </head> <script> window.onload = function () { // type型のfileの要素を取得 let tf = document.getElementById("dp"); // 表示用の要素を取得 let objs= document.getElementsByClassName('cft')[0]; tf.addEventListener('change', (e) => { const target = event.target; const files = target.files; const file = files[0]; let read = new FileReader(); // ファイルの内容を表示 read.readAsText(file); read.onload = function() { objs.textContent = read.result; }; read.onerror = function() { // ファイルの読み込みを失敗する場合 console.log(read.error); }; }); } </script> <body> <h2>ファイルの内容:<span class="cft"></span></h2> <form> <input type="file" id="dp" accept=".csv"> </form> </body> </html>
<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>CSVファイルを読み込むサンプル</title>

</head>
<script>

  window.onload = function () {
    // type型のfileの要素を取得
    let tf = document.getElementById("dp");

    // 表示用の要素を取得
    let objs= document.getElementsByClassName('cft')[0];

    tf.addEventListener('change', (e) => {

      const target = event.target;
      const files = target.files;
      const file = files[0];
      
      let read = new FileReader();

      // ファイルの内容を表示
      read.readAsText(file);
      read.onload = function() {
        objs.textContent = read.result;
      };

      read.onerror = function() {
        //  ファイルの読み込みを失敗する場合
        console.log(read.error);
      };
      
    });
  }

</script>

<body>
    <h2>ファイルの内容:<span class="cft"></span></h2>
    <form>
        <input type="file"  id="dp" accept=".csv">
    </form>

</body>

</html>

実行結果
「ファイルを選択」ボタンを押して「test01.csv」を選択します。
画面に「ファイルの内容:yamada,20,tokyo」が表示されます。

JavaScript

Posted by arkgame