2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSVファイルをドラッグ&ドロップでデータをtable表示

Last updated at Posted at 2018-08-31
base.html
<div id="drop_wrap">
<p>ファイルをドロップしてください</p>
</div>
<table id="data_result">
  <thead>
    <th>見出し1</th>
    <th>見出し2</th>
    <th>見出し3</th>
    <th>見出し4</th>
  </thead>
  <tbody>
    <!-- ここにCSVデータ表示  -->
  </tbody>
</table>
style.css
#drop_wrap {
    display: block;
    border: 2px dashed #bbb;
    border-radius: 5px;
    color: #bbb;
    padding: 25px;
    text-align: center;
    margin: 10px auto 5px;
    font-size: 18px;
    font-weight: bold;
    -khtml-user-drag: element;
    margin: 5% auto;
    width: 80%;
}
script.js
$(function(){
  // FileAPIでCSVファイルのドロップ出力処理
   $("#drop_wrap").on("drop", function(e) {
       e.preventDefault();
       var $result_body = $('#data_result tbody');
       var files = e.originalEvent.dataTransfer.files[0];
       var reader = new FileReader();
       reader.onload = function(event) {
           // " "ごとに分割して配列化
           var lineArr = event.target.result.split(" ");
           // 行と列の二次元配列にする
           var itemArr = [];
           for (var i = 0; i < lineArr.length; i++) {
               itemArr[i] = lineArr[i].split(",");
           }
           // tableタグで出力
           var insert = '';
           for (var i = 0; i < itemArr.length; i++) {
               insert += '<tr>';
               for (var j = 0; j < itemArr[i].length; j++) {
                     insert += '<td>' + itemArr[i][j] + '</td>';
               }
               insert += '</tr>';
           }
           $result_body.html(insert);
       }

       reader.readAsText(files, 'Shift_JIS');
   }).on("dragenter", function() {
       return false;
   }).on("dragover", function() {
       return false;
   });
});
2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?