Похоже, у вас CSV
в соответствии RFC4180 .Там Определение формата CSV гласит:
Поля, содержащие разрывы строк (CRLF), двойные кавычки и запятые, должны быть заключены в двойные кавычки.Например:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
Это сложнее простого CSV и не может быть просто прочитано построчно, поскольку не каждый перевод строки означает новую запись.Попробуйте найти анализатор CSV, который поддерживает RFC4180.
opencsv будет таким.
Пример:
CSV.csv:
Field1,Field2,Field3
123,This is test column.,345
678,"This is test column.
This is next line",910
123,This is test column.,345
Код:
import java.io.FileOutputStream;
import java.io.FileReader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.opencsv.CSVReader;
class ParseCSVToExcel {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream out = new FileOutputStream("Excel.xlsx");
FileReader in = new FileReader("CSV.csv")) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
Sheet sheet = workbook.createSheet("FromCSV");
Row row = null;
Cell cell = null;
int r = 0;
int maxC = 0;
CSVReader reader = new CSVReader(in);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
row = sheet.createRow(r++);
int c = 0;
for (String field : nextLine) {
cell = row.createCell(c++);
cell.setCellValue(field);
cell.setCellStyle(cellStyle);
}
if (c > maxC) maxC = c;
}
for (int c = 0; c < maxC; c++) {
sheet.autoSizeColumn(c);
}
workbook.write(out);
}
}
}
Результат:
![enter image description here](https://i.stack.imgur.com/zn2b8.png)
Использование Apache Commons CSV была бы другая возможность.
То же CSV.csv
, как указано выше.
Код:
import java.io.FileOutputStream;
import java.io.FileReader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.CSVFormat;
class ParseCSVToExcelApacheCommonsCSV {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream out = new FileOutputStream("Excel.xlsx");
FileReader in = new FileReader("CSV.csv")) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
Sheet sheet = workbook.createSheet("FromCSV");
Row row = null;
Cell cell = null;
int r = 0;
int maxC = 0;
for (CSVRecord record : CSVFormat.RFC4180.parse(in)) {
row = sheet.createRow(r++);
int c = 0;
for (String field : record) {
cell = row.createCell(c++);
cell.setCellValue(field);
cell.setCellStyle(cellStyle);
}
if (c > maxC) maxC = c;
}
for (int c = 0; c < maxC; c++) {
sheet.autoSizeColumn(c);
}
workbook.write(out);
}
}
}
Тот же результат, что и выше.