Java CSV File Parse parseExcelCSVLine(String line)

Here you can find the source of parseExcelCSVLine(String line)

Description

Reads a line of text in the Excel CSV format
Each field is separated by a comma, except some fields have quotes around them because the field has commas or spaces.
TODO: Test to see how quotes within fields are treated

License

Open Source License

Parameter

Parameter Description
line Description of the Parameter

Return

Description of the Return Value

Declaration

public static ArrayList parseExcelCSVLine(String line) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

public class Main {
    /**//w ww  . java 2s  . c  o  m
     * Reads a line of text in the Excel CSV format<br>
     * Each field is separated by a comma, except some fields have quotes around
     * them because the field has commas or spaces.<br>
     * TODO: Test to see how quotes within fields are treated
     *
     * @param line Description of the Parameter
     * @return Description of the Return Value
     */
    public static ArrayList parseExcelCSVLine(String line) {
        if (line == null) {
            return null;
        }
        ArrayList thisRecord = new ArrayList();
        boolean quote = false;
        boolean completeField = false;
        StringBuffer value = new StringBuffer("");
        for (int i = 0; i < line.length(); i++) {
            char thisChar = line.charAt(i);
            if (thisChar == ',') {
                if (quote == false) {
                    completeField = true;
                } else {
                    value.append(thisChar);
                }
            } else if (thisChar == '\"') {
                if (quote) {
                    quote = false;
                } else {
                    quote = true;
                }
            } else {
                value.append(thisChar);
            }
            if (i == line.length() - 1) {
                completeField = true;
            }
            if (completeField) {
                thisRecord.add(value.toString());
                value = new StringBuffer("");
                quote = false;
                completeField = false;
            }
        }
        return thisRecord;
    }

    /**
     * Description of the Method
     *
     * @param s Description of Parameter
     * @return Description of the Returned Value
     */
    public static String toString(String s) {
        if (s != null) {
            return (s);
        } else {
            return ("");
        }
    }
}

Related

  1. parseCSVIntegers(String csv)
  2. parseCsvLine(final String line)
  3. parseCSVLine(String CSVLine, char delimChar, char quotChar)
  4. parseCsvRecord(String record, char csvSeparator)
  5. parseCsvString(String toParse)
  6. parseLine(String csvLine)