2014-02-26 32 views
4

有很多使用jQuery讀取CSV文件的示例,但是javascript示例很少和很多。使用Javascript將CSV文件讀取到關鍵值對數組中

由於我正在使用特定應用程序的內部腳本編輯器,我僅限於使用Javascript。

我有一個csv文件,其標題後面跟着每行數據。

Heading1,Heading2,Heading3,Heading4 
row1data1,row1data2,row1data3,row1data4 
row2data1,row2data2,row2data3,row2data4 

正在使用的分隔符是,但是也可能有其他的例如^

由於我無法上傳文件,我可以選擇手動引用絕對路徑。

有沒有一種方法,我可以只使用JavaScript來讀取一個CSV文件?

+1

你問如何閱讀的JavaScript文件?或者如何解析你在javascript中的大字符串爲CSV? –

+0

您可以使用ajax/text獲取csv,然後用換行符分割它,然後用逗號分割 – SajithNair

+0

@Sajith Nair - 我無法使用AJAX。我僅限於簡單的ol'javascript – PeanutsMonkey

回答

14

作爲開始,這裏是一對夫婦的方式閱讀的JavaScript文件

的HttpRequest:(從Web服務器或絕對路徑)

來源:Javascript - read local text file

function readTextFile(file) 
{ 
    var rawFile = new XMLHttpRequest(); 
    rawFile.open("GET", file, true); 
    rawFile.onreadystatechange = function() 
    { 
     if(rawFile.readyState === 4) 
     { 
      if(rawFile.status === 200 || rawFile.status == 0) 
      { 
       var allText = rawFile.responseText; 
       alert(allText); 
      } 
     } 
    } 
    rawFile.send(null); 
} 

,並指定file://在你的文件名中使用絕對路徑時

readTextFile("file:///C:/your/path/to/file.txt"); 

的FileReader API:

來源:
- http://codepen.io/matt-west/pen/KjEHg
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

HTML

<div id="page-wrapper"> 

    <h1>Text File Reader</h1> 
    <div> 
     Select a text file: 
     <input type="file" id="fileInput"> 
    </div> 
    <pre id="fileDisplayArea"><pre> 

</div> 

JS

window.onload = function() { 
    var fileInput = document.getElementById('fileInput'); 
    var fileDisplayArea = document.getElementById('fileDisplayArea'); 

    fileInput.addEventListener('change', function(e) { 
     var file = fileInput.files[0]; 
     var textType = /text.*/; 

     if (file.type.match(textType)) { 
      var reader = new FileReader(); 

      reader.onload = function(e) { 
       fileDisplayArea.innerText = reader.result; 
      } 

      reader.readAsText(file);  
     } else { 
      fileDisplayArea.innerText = "File not supported!" 
     } 
    }); 
} 

JS在MS Windows(簡單的樣品)

來源:http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx

function ReadFiles() 
{ 
    var fso, f1, ts, s; 
    var ForReading = 1; 
    fso = new ActiveXObject("Scripting.FileSystemObject"); 
    ts = fso.OpenTextFile("c:\\testfile.txt", ForReading); 
    s = ts.ReadLine(); 
    // s holds the text content 
    ts.Close(); 
} 
+0

@PellePenna - 抱歉PellePenna。該應用程序不支持XMLHTTPRequest或HTML和JS的組合。它需要是直接JavaScript。 – PeanutsMonkey

+0

我更新了我的答案,底部是如何在Windows計算機上使用它。您必須測試UNC路徑是否可行。如果沒有,你必須分配一封信到一個路徑,這當然可以做到IP和本地網絡計算機 – LGSon

+0

@PellePenna - 謝謝PellePenna。你給的最後一個例子像一個魅力工作 – PeanutsMonkey

相關問題