【发布时间】:2021-03-22 09:54:42
【问题描述】:
如果字段中有逗号,但整体用引号括起来,那么我不应该将其视为列分隔符。如何做到这一点?
例如 aaaa, "bb,bb", cccc 我得到 aaaa | bb | bb |ccc
我怎样才能收到aaaa | "bb,bb" |抄送?
public List<CSVRecord> collectAllEntries(Path path) throws IOException {
logger.info("Parsing the input file" + path);
List<CSVRecord> store = new ArrayList<>();
try (
Reader reader = Files.newBufferedReader(path, Charset.forName("ISO-8859-2"));
CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withQuote(';'))
) {
for (CSVRecord csvRecord : csvParser) {
store.add(csvRecord);
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
return store;
}
private void csvToXlsx(Path csvFilePath, Path excelFilePath) throws Exception {
logger.info("Converting CSV to XLSX" + excelFilePath);
List<CSVRecord> records = collectAllEntries(csvFilePath);
XSSFWorkbook myWorkBook = new XSSFWorkbook();
FileOutputStream writer = new FileOutputStream(new File(excelFilePath.toString()));
XSSFSheet mySheet = myWorkBook.createSheet();
IntStream.range(0, records.size())
.forEach(rowNum -> {
XSSFRow myRow = mySheet.createRow(rowNum);
CSVRecord record = records.get(rowNum);
for (int i = 0; i < record.size(); i++) {
XSSFCell myCell = myRow.createCell(i);
myCell.setCellValue(record.get(i));
}
});
myWorkBook.write(writer);
writer.close();
}
【问题讨论】:
-
检查“,当检测到它时,您需要将所有内容视为严格字符串,直到检测到另一个“。您可以为此使用状态。
-
CSVFormat.EXCEL.withQuote(';')这不是正确的引号字符。最好使用已经有正确设置的CSVFormat.EXCEL -
@Aaron 所以我必须将其设置为包含报价?像这样 ? CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withQuote('"').withDelimiter(';'))
-
我只使用
CSVFormat.EXCEL,查看我之前评论中的链接,您会看到它的默认配置适合您的数据(withDelimiter(','),withQuote('"')) -
@Aaron 以前,我只使用 CSVFormat.EXCEL 配置,但它对我不起作用。它可能取决于编码吗?或者这个方法可能是错误的 csvToXlsx?