0

I am converting CSV to XLSX using this code

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");
    }

One of the column in CSV file has one line break another line using this str.length it is taking separate separate line i want to take that whole column value.

CSV to XLSX

I want to take whole column value and writ it into XLSX file.

  • Hi Please try link where exact issue has been resolved. https://stackoverflow.com/q/18077264/8148899 – Jitendra Banshpal Jan 21 '19 at 10:56
  • I have used that code only but the issue is see screen shot attached. str.length counting until "This is test column" and create one column write that sting to that column and has followed for "This is next line". My question is that should read entire column value and write entire value into single column not in 2 column separately – Priya Dharshan Jan 21 '19 at 11:00
  • Please understand internal structure of CSV as you have seporated using comma it read it as a single row ,If you want a better knowledge please open your csv in text pad and look how it is – KishanCS Jan 21 '19 at 11:03
  • It is separated by comma(,) correctly but it is not taking entire string until comma(,) ends as entire column. Please help me to over this issue – Priya Dharshan Jan 21 '19 at 11:08
  • So do you want you text "This is test column:" and "this is next line " in single cell or in diffrent cell in xlsx?. – KishanCS Jan 21 '19 at 11:27
  • Single cell in xlsx. because due to this line break my total excel sheet has collapsed – Priya Dharshan Jan 21 '19 at 11:30
  • You seems to have a `CSV` according [RFC4180](https://tools.ietf.org/html/rfc4180#section-2) - "6. Fields containing line breaks (CRLF)...". This is more complex than a simple `CSV` and cannot simply be read line by line then. Try finding a `CSV` parser which supports RFC4180. – Axel Richter Jan 21 '19 at 13:01
  • Can you help me to read particular column alone not entire column this is another way i found to solve my problem – Priya Dharshan Jan 21 '19 at 13:06

2 Answers2

2

You seems to have a CSV according RFC4180. There Definition of the CSV Format states:

  1. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example:

      "aaa","b CRLF
       bb","ccc" CRLF
       zzz,yyy,xxx
    

This is more complex than a simple CSV and cannot simply be read line by line then since not each linefeed means a new record. Try finding a CSV parser which supports RFC4180.

opencsv will be a such.

Example:

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

Code:

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);

  }
 }
}

Result:

enter image description here


Using Apache Commons CSV would be another possibility.

Same CSV.csvas above.

Code:

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);

  }
 }
}

Same result as above.

Community
  • 1
  • 1
Axel Richter
  • 56,077
  • 6
  • 60
  • 87
  • Sorry for delay now only i have run your code it's working fine. Thanks Axel Richter – Priya Dharshan Feb 04 '19 at 14:27
  • One more doubt i have to remove 1st row in excel sheet i have tried using removeRow & shiftRows but it is removing only values not entire row can you please me to solve this issue – Priya Dharshan Feb 04 '19 at 14:54
-1

Where new line is coming add this bellow code for that string value

    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    currentRow.createCell(i).setCellStyle(cs);
vivekdubey
  • 484
  • 2
  • 7
  • 1
    I am doing dynamically so i don't know where single line is coming. Can you please edit my above code for my better understanding. In your code wb refers to workbook or what? – Priya Dharshan Jan 21 '19 at 11:10