Получить строку после разрыва в файле CSV столбца, используя Java Apache Poi - PullRequest
0 голосов
/ 21 января 2019

Я конвертирую CSV в XLSX, используя этот код

try {
        String home = System.getProperty("user.home");
        File file = new File(home+"/Downloads/test.csv");
        File file1 = new File(home+"/Downloads/test1.xlsx");
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet("sheet1");
        String currentLine=null;
        int RowNum=0;
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((currentLine = br.readLine()) != null) {
            String str[] = currentLine.split(",");
            RowNum++;
            XSSFRow currentRow=sheet.createRow(RowNum);
            for(int i=0;i<str.length;i++){
                System.out.println(str[i]+"/n");
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }

        FileOutputStream fileOutputStream =  new FileOutputStream(file1);
        workBook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("Done");
    } catch (Exception ex) {
        System.out.println(ex.getMessage()+"Exception in try");
    }

В одном из столбцов в файле CSV одна строка разбивает другую строку, используя эту длину строки. Она занимает отдельную отдельную строку.значение всего столбца.

CSV to XLSX

Я хочу взять значение целого столбца и записать его в файл XLSX.

Ответы [ 2 ]

0 голосов
/ 21 января 2019

Похоже, у вас 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


Использование 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);

  }
 }
}

Тот же результат, что и выше.

0 голосов
/ 21 января 2019

Если появится новая строка, добавьте следующий код для этого строкового значения

    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    currentRow.createCell(i).setCellStyle(cs);
...