Issues converting csv to xls in Java? Only core Java experience needed - question not related to import

后端 未结 4 1492
甜味超标
甜味超标 2020-12-22 08:35

First of all, I understand that it\'s unusual that I want to up-convert like this, but please bear with me. We get these csv files via website export and we have no options

4条回答
  •  情歌与酒
    2020-12-22 08:58

    Just check the CSV char by char and set a toggle whenever a quote occurs. Here's a kickoff example:

    public static List> parseCsv(InputStream input, char separator) 
        throws IOException 
    {
        BufferedReader reader = null;
        List> csv = new ArrayList>();
        try {
            reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            for (String record; (record = reader.readLine()) != null;) {
                boolean quoted = false;
                StringBuilder fieldBuilder = new StringBuilder();
                List fields = new ArrayList();
                for (int i = 0; i < record.length(); i++) {
                    char c = record.charAt(i);
                    fieldBuilder.append(c);
                    if (c == '"') {
                        quoted = !quoted;
                    }
                    if ((!quoted && c == separator) || i + 1 == record.length()) {
                        fields.add(fieldBuilder.toString().replaceAll(separator + "$", "")
                            .replaceAll("^\"|\"$", "").replace("\"\"", "\"").trim());
                        fieldBuilder = new StringBuilder();
                    }
                }
                csv.add(fields);
            }
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
        }
        return csv;
    }
    

    You can however also just grab any 3rd party Java CSV API which may have some more features and so on.

提交回复
热议问题