Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - How to read Excel(.xlsx) Multipartfile using Apache CSV Parser?. Current approach not working with CSVFormat set to EXCEL

I'm trying to read records for both CSV as well as Excel format using Apache CSVParser. Below is my approach for the same.

try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(),
                                                                              StandardCharsets.UTF_8)) {
            CSVParser parser;
            String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
            logger.info("Extension Detected : {}", extension);
            if (extension != null && extension.equals("xlsx")) {
                parser = new CSVParser(reader,
                                       CSVFormat.EXCEL.withFirstRecordAsHeader().withTrim());
            } else if(extension != null && extension.equals("csv")){
                parser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader()
                                                                .withIgnoreHeaderCase().withTrim());
            } else {
                throw new InvalidRequestException(Collections.singletonList(INVALID_EXTENSION));
            }
            logger.info("Records parsed successfully for file : {}", file.getOriginalFilename());
            return parser.getRecords();
        } catch (IOException e) {
            throw new FileReadException(e);
        }

This is working for CSV Files but not for Excel. Parser is not able to read the records properly. Here's the debugged value of parser.

enter image description here

I feel it's related to reusableToken because in case of CSV, Token Type is TOKEN , But in case of Excel it's EORecord.

Can anybody please help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Apache CSVParser can't parse Excel files, only csv files. Using the CSVFormat.EXCEL parameter just tells CSVParser that the csv file was created/exported using Excel.

To read xls & xlsx files you need to use Apache POI.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...