0

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

1
  • 4
    By studying docs/tutorials and starting to write code and try experimenting?! Commented Nov 11, 2016 at 8:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the advice first splitting at \n- I tried splitting at ,and then write the Excel - if I come up with working Code i will post it here
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.