Program Tip

CSV 파일에 대해 쉼표와 큰 따옴표를 동시에 이스케이프하는 방법은 무엇입니까?

programtip 2020. 11. 26. 19:45
반응형

CSV 파일에 대해 쉼표와 큰 따옴표를 동시에 이스케이프하는 방법은 무엇입니까?


Oracle에서 csv 파일로 데이터를 내보내는 Java 앱을 작성 중입니다.

불행히도 데이터의 내용은 매우 까다로울 수 있습니다. 여전히 쉼표가 구분자이지만 행의 일부 데이터는 다음과 같을 수 있습니다.

ID FN LN 나이 COMMENT

123, John, Smith, 39, "Hey, I am 5'10"라고 말했습니다.

따라서 이것은 comment열의 문자열 중 하나입니다 .

"이봐, 난 5시 10 분이야"라고 했어요. "

농담이 아닙니다. Java에서 생성 한 CSV 파일의 Excel 또는 Open Office에서 타협하지 않고 위의 주석을 표시해야합니다. 물론 다른 일반 이스케이프 상황 (예 : 일반 큰 따옴표 및 튜플 내의 일반 쉼표)을 엉망으로 만들 수 없습니다. 정규 표현식이 강력하다는 건 알지만 이렇게 복잡한 상황에서 어떻게 목표를 달성 할 수 있을까요?


여러 라이브러리가 있습니다. 다음은 두 가지 예입니다.


Apache Commons Lang ❐

Apache Commons Lang 에는 문자열 (CSV, EcmaScript, HTML, Java, Json, XML)을 이스케이프하거나 이스케이프 해제하는 특수 클래스가 포함되어 org.apache.commons.lang3.StringEscapeUtils있습니다..

  • CSV로 이스케이프

    String escaped = StringEscapeUtils
        .escapeCsv("I said \"Hey, I am 5'10\".\""); // I said "Hey, I am 5'10"."
    
    System.out.println(escaped); // "I said ""Hey, I am 5'10""."""
    
  • CSV에서 이스케이프 해제

    String unescaped = StringEscapeUtils
        .unescapeCsv("\"I said \"\"Hey, I am 5'10\"\".\"\"\""); // "I said ""Hey, I am 5'10""."""
    
    System.out.println(unescaped); // I said "Hey, I am 5'10"."
    

* 여기 에서 다운로드 할 수 있습니다 .


OpenCSV ❐

OpenCSV 를 사용하는 경우 내용을 쓰거나 읽을 때만 이스케이프 또는 이스케이프 해제에 대해 걱정할 필요가 없습니다.

  • 파일 쓰기 :

    FileOutputStream fos = new FileOutputStream("awesomefile.csv"); 
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    CSVWriter writer = new CSVWriter(osw);
    ...
    String[] row = {
        "123", 
        "John", 
        "Smith", 
        "39", 
        "I said \"Hey, I am 5'10\".\""
    };
    writer.writeNext(row);
    ...
    writer.close();
    osw.close();
    os.close();
    
  • 파일 읽기 :

    FileInputStream fis = new FileInputStream("awesomefile.csv"); 
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    CSVReader reader = new CSVReader(isr);
    
    for (String[] row; (row = reader.readNext()) != null;) {
        System.out.println(Arrays.toString(row));
    }
    
    reader.close();
    isr.close();
    fis.close();
    

* 여기 에서 다운로드 할 수 있습니다 .


Excel은 똑같은 상황을 처리 할 수 ​​있어야합니다.

이러한 항목을 Excel에 넣고 CSV로 저장하고 텍스트 편집기로 파일을 검토합니다. 그러면 Excel이 이러한 상황에 적용하는 규칙을 알게 될 것입니다.

Java가 동일한 출력을 생성하도록합니다.

그런데 Excel에서 사용하는 형식이 게시됩니다.

****Edit 1:**** Here's what Excel does
****Edit 2:**** Note that php's fputcsv does the same exact thing as excel if you use " as the enclosure.

rdeslonde@mydomain.com
Richard
"This is what I think"

gets transformed into this:

Email,Fname,Quoted  
rdeslonde@mydomain.com,Richard,"""This is what I think"""

Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:

if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
    cell_value = cell_value.replaceAll("\"", "\"\"");
    row.append("\"");
    row.append(cell_value);
    row.append("\"");
} else {
    row.append(cell_value);
}

in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\"") by adding additional double quote (like "\"\""), then put the whole thing into a double quote (like "\""+theWholeThing+"\"" )


You could also look at how Python writes Excel-compatible csv files.

I believe the default for Excel is to double-up for literal quote characters - that is, literal quotes " are written as "".


"cell one","cell "" two","cell "" ,three"

Save this to csv file and see the results, so double quote is used to escape itself

Important Note

"cell one","cell "" two", "cell "" ,three"

will give you a different result because there is a space after the comma, and that will be treated as "


If you're using CSVWriter. Check that you don't have the option

.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)

When I removed it the comma was showing as expected and not treating it as new column


String stringWithQuates = "\""+ "your,comma,separated,string" + "\"";

this will retain the comma in CSV file

참고URL : https://stackoverflow.com/questions/10451842/how-to-escape-comma-and-double-quote-at-same-time-for-csv-file

반응형