java 讀取 CSV , 內容有 逗號 處理

 java 讀取 CSV 逗號 處理

V 1.

https://www.itread01.com/content/1542647890.html

最近在公司寫專案時,有個匯入csv格式檔案資料的需求。Java讀取csv檔案時預設是按照 ,[英文逗號]分割的,若是資料內容不包含逗號的話就簡單多了,但遇到的問題就恰巧是尷尬的地方。

解決方案

覺得比較好的解決方案就是使用正則進行匹配,讀取的csv資料預設是用雙引號包起來的,在最後的擷取中,如果只按照雙引號外的逗號擷取,不就是能得到想要的資料了。

                    //資料資訊
                    listField = new ArrayList<>();
                    String str;
                   
                    line += ",";               
                    Pattern pCells = Pattern
                            .compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
                    Matcher mCells = pCells.matcher(line);
                    List cells = new LinkedList();//每行記錄一個list
                    //讀取每個單元格
                    while (mCells.find()) {
                        str = mCells.group();
                        str = str.replaceAll(
                                "(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");
                        str = str.replaceAll("(?sm)(\"(\"))", "$2");
                        cells.add(str);
                    }
                    //從第2行起的資料資訊list
                    listField.add(cells);
                }
                lineNum++;


2.
https://t.codebug.vip/questions-2524884.htm

V 3. 

Java 读取csv文件 包含 逗号

String[] fields = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

https://blog.csdn.net/qq_21113625/article/details/105709372

4.

我建議你使用http://opencsv.sourceforge.net/。如果您的CSV文件源文件格式正確,它將爲您處理所有內容。

用法示例:

InputStream csvStream = getAssets().open(yourCSVFile); 
     InputStreamReader csvStreamReader = new InputStreamReader(csvStream); 
     CSVReader csvReader = new CSVReader(csvStreamReader); 
     String[] line; 

     while ((line = csvReader.readNext()) != null) { 
        String example = line[0]; // first item of your csv row 
        } 

http://hk.uwenku.com/question/p-dgcnkdow-su.html

** OpenCsv **解決了這個問題。我使用他以下代碼 'CSVReader reader = new CSVReader(new FileReader(「yourfile.csv」)); String [] nextLine; 而((nextLine = reader.readNext())!= NULL){ // nextLine []是值從行的陣列 的System.out.println(nextLine [0] + nextLine [1] +「等等......」); }' – isumit

5.

http://hk.uwenku.com/question/p-dgcnkdow-su.html
 

我建議使用RegEx進行分割。你可以使用類似的東西:\"(.*?)\",?

我沒有在我使用的計算機上的Java安裝程序,但像這樣應該工作。不能保證它會編譯。

String myString = "\"name of user\",\"official address, city\",\"2740740, 2740608\",,\"address, city, state\"" 

Pattern myPattern = Pattern.compile("\"(.*?)\",?"); 
Matcher myMatcher = myPattern.matcher(myString); // myPattern to match against string 
while (myMatcher.find()) 
{ 
    System.out.println(myMatcher.group(1)); 
} 


6.
向量的方法
https://wellbay.cc/thread-2052661.htm


V 7.
https://www.jianshu.com/p/4d47e2f3c75f

留言

這個網誌中的熱門文章

考績被打差了 輕率離職會更傷

Arrays - DS (Reverse array) [Easy]

WireMock