KilledByCHeese
KilledByCHeese

Reputation: 872

Java write csv-String to Excel

in my program i want to write an String to *.xlsx

Example for the String:

a,b,c,d,e,,f,\na,b,c,d,e,,f,\n

I want to write an Excel file which looks like this:enter image description here

How can I do this?

private void createExcel() throws Exception {
    //Create blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook(); 
    //Create a blank sheet
    XSSFSheet spreadsheet = workbook.createSheet("Excel Sheet");

How can I create the rows and columns from my csvString?

    //Write the workbook in file system
    FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
    workbook.write(out);
    out.close();
    System.out.println("*.xlsx written successfully" );
}

I'm thankful for any help

Upvotes: 0

Views: 2031

Answers (2)

KilledByCHeese
KilledByCHeese

Reputation: 872

private void createExcel() throws Exception {
    //Create blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook(); 
    //Create a blank sheet
    XSSFSheet spreadsheet_1 = workbook.createSheet("Excel Sheet");

    ArrayList<String> arrRows = new ArrayList<String>(Arrays.asList(Text.split("\n")));

    for (int i = 0; i < arrRows.size(); i++) {

        XSSFRow row = spreadsheet_1.createRow(i);

        ArrayList<String> arrElement = new ArrayList<String>(Arrays.asList(arrRows.get(i).split(",")));

        for(int j = 0; j < arrElement.size(); j++) {

            XSSFCell cell = row.createCell(j);
            cell.setCellValue(arrElement.get(j));

        }           
    }
    //Write the workbook in file system
    FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
    workbook.write(out);
    out.close();
    System.out.println("*.xlsx written successfully" );
}

Like @Naveed S said first I split my Text at every \N and create a Row for each element. Then I Split the elements at ,and create Cells

Thanks for the help and suggestion it really helped me

Upvotes: 0

Naveed S
Naveed S

Reputation: 5236

Using XSSFSheet.createRow(), you can create rows as required.

In your case, you would have to split the string by ,\n and make a XSSFSheet.createRow() call for each element of the resulting array.

Using XSSFRow.createCell(), you can create cells, for which a split by , would be required. To set the value, Cell.setCellValue() has to be invoked with each comma separated part.

Simple example here.

Upvotes: 1

Related Questions