2013-11-19 1 views
1

Это код, который читает текстовый файл с помощью Jscript и отображает его в HTML. Но мне нужно, чтобы он отображался в таблице.

Как отобразить его в таблице. < это мой первый вопрос, так что я надеюсь, что я получаю решение>Как прочитать текстовый файл с использованием Java-скрипта и отобразить его в виде столбцов в HTML.?

` Чтение файла (с помощью выбора ввода пользователя) вар читателя; // глобальный объект чтения файла для демонстрационной цели только

/** 
    * Check for the various File API support. 
    */ 
    function checkFileAPI() { 
     if (window.File && window.FileReader && window.FileList && window.Blob) { 
      reader = new FileReader(); 
      return true; 
     } else { 
      alert('The File APIs are not fully supported by your browser. Fallback required.'); 
      return false; 
     } 
    } 

    /** 
    * read text input 
    */ 
    function readText(filePath) { 
     var output = ""; //placeholder for text output 
     if(filePath.files && filePath.files[0]) {   
      reader.onload = function (e) { 
       output = e.target.result; 
       displayContents(output); 
      };//end onload() 
      reader.readAsText(filePath.files[0]); 
     }//end if html5 filelist support 
     else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX 
      try { 
       reader = new ActiveXObject("Scripting.FileSystemObject"); 
       var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object 
       output = file.ReadAll(); //text contents of file 
       file.Close(); //close file "input stream" 
       displayContents(output); 
      } catch (e) { 
       if (e.number == -2146827859) { 
        alert('Unable to access local files due to browser security settings. ' + 
        'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
        'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
       } 
      }  
     } 
     else { //this is where you could fallback to Java Applet, Flash or similar 
      return false; 
     }  
     return true; 
    } 

    /** 
    * display content using a basic HTML replacement 
    */ 
    function displayContents(txt) { 
     var el = document.getElementById('main'); 
     el.innerHTML = txt; //display output in DOM 
    } 
</script> 
</head> 
<body onload="checkFileAPI();"> 
    <div id="container">  
     <input type="file" onchange='readText(this)' /> 
     <br/> 
     <hr/> 
     <h3>Contents of the Text file:</h3> 
     <div id="main"> 
      ... 
     </div> 
    </div> 
</body> 
</html>` 

Пожалуйста, помогите мне в этом

+1

Какой текст есть в текстовом файле? Можно ли его читать как табличные данные? Или вам нужен всего текст внутри одной ячейки таблицы? – dljve

+0

Ya можно читать как табличные данные. –

+0

Фактически Весь текстовый файл контакт 3 таблицы, я должен отображать его в интерфейсе html. –

ответ

0

Вы можете отформатировать текстовый файл, как в SSV (TSV или CSV, а), то вместо ReadAll() я бы сделать что-то вроде этого:

var file = reader.OpenTextFile(filePath, 1), 
    data = [], n; 
while (!file.AtEndOfStream) { 
    data.push(file.ReadLine().split(';')); // or use some other "cell-separator" 
} 

Тогда остальное намного проще и быстрее, если у вас есть пустой table элемент в вашем HTML:

<table id="table"></table> 

Теперь просто создавать строки и ячейки динамически на основе data массива:

var table = document.getElementById('table'), 
    len = data.length, 
    r, row, c, cell; 
for (r = 0; r < len; r++) { 
    row = table.insertRow(-1); 
    for (c = 0; c < data[r].lenght; r++) { 
     cell.row.insertCell(-1); 
     cell.innerHTML = data[r][c]; 
    } 
}