2017-01-02 67 views
3

嗨我有一個CSV文件,其中的封裝器字符未正確轉義。解析CSV文件,其中內容中的封裝器沒有正確轉義

[email protected],"uhrege gerjhhg er<span style="background-color: rgb(0,153,0);">eriueiru kernger</span><font color="#009900"><span style="background-color: rgb(255,255,255);"> weiufhuweifbw fhew fibwefbw</span></font><div><font color="#009900"><span style="background-color: rgb(255,255,255);">wekifbwe fewf</span></font></div><div><font color="#009900"><span style="background-color: rgb(255,255,255);">weiuifgewbfjew f</span></font></div>",18-Oct-2016, 

分隔符 - >,

封裝器 - >「

它打破了,當我嘗試使用公地CSV讀卡器, 拋出一個 'invalid char between encapsulated token and delimiter' 異常閱讀

但是,Microsoft Excel似乎完美地打開文件。 關於如何procc的任何想法編輯? 。

如何解析封裝程序未正確轉義的CSV文件?.Excel似乎打開這樣的文件很好。

+1

我發現這個有用http://stackoverflow.com/questions/15210568/java-csv-parser-with-unescaped-quotes自由職業辦公室和Excel似乎是採取有教養的猜測。我怎樣才能做到這一點? –

回答

1

如果你不能修復這個源頭(即產生一個結構良好的CSV),並要在此分析自己,你可以去簡單的方法:

掃描FIELD1高達," - 場2最多", - 其餘是field3(尾隨逗號?)。

當然,如果在html字段中出現",,則會出現問題。你可以通過首先掃描到,",然後倒退(從行的末尾開始)到",來解決這個問題。

如果有更多的領域比你在這裏展示,你可以找一個,"組合(包括組合,也可能是","),並希望那些沒有出現在現場數據。

0

univocity-parsers有一個CSV解析器,可以正確處理這種輸入。

//first configure the parser 
    CsvParserSettings settings = new CsvParserSettings(); 
    settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.STOP_AT_CLOSING_QUOTE); 

    //then create a parser and parse your input line: 
    CsvParser parser = new CsvParser(settings); 
    String[] result = parser.parseLine("" + 
      "[email protected],\"uhrege gerjhhg er<span style=\"background-color: rgb(0,153,0);\">eriueiru kernger</span><font color=\"#009900\"><span style=\"background-color: rgb(255,255,255);\"> weiufhuweifbw fhew fibwefbw</span></font><div><font color=\"#009900\"><span style=\"background-color: rgb(255,255,255);\">wekifbwe fewf</span></font></div><div><font color=\"#009900\"><span style=\"background-color: rgb(255,255,255);\">weiuifgewbfjew f</span></font></div>\",18-Oct-2016,"); 

    //here's the result (one value per line) 
    for (String v : result) { 
     System.out.println(v); 
    } 

此打印:

[email protected] 
uhrege gerjhhg er<span style="background-color: rgb(0,153,0);">eriueiru kernger</span><font color="#009900"><span style="background-color: rgb(255,255,255);"> weiufhuweifbw fhew fibwefbw</span></font><div><font color="#009900"><span style="background-color: rgb(255,255,255);">wekifbwe fewf</span></font></div><div><font color="#009900"><span style="background-color: rgb(255,255,255);">weiuifgewbfjew f</span></font></div> 
18-Oct-2016 
null 

希望它能幫助。

聲明:我是該庫的作者。它是開源的和免費的(Apache v2.0許可證)