0

I am new to Excel - Java (Apache POI) and trying to figure out a way to transfer excel data to a text file.

My excel sheet looks something like this

     name   table   latest_table   Date
1   george  table1  t459           2017-08-24
2   john    table1  thi7           2017-07-23
3   mary    table1  gdr99          2017-07-22

My Code so far

public static void excel_to_text(XSSFWorkbook wb) {
        XSSFSheet sheet = wb.getSheetAt(0);
         int rows = sheet.getPhysicalNumberOfRows();
         int cols = 0, tmp = 0;
         XSSFRow row;
         XSSFCell cell;

         for(int i = 0; i < 10 || i < rows; i++) {
                row = sheet.getRow(i);
                if(row != null) {
                    tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                    if(tmp > cols) cols = tmp;
                }
            }

            for(int r = 0; r < rows; r++) {
                row = sheet.getRow(r);
                if(row != null) {
                    for(int c = 0; c < cols; c++) {
                        cell = row.getCell((short)c);
                        if(cell != null) {
                            *// code here*
                        }
                    }
                }
            }

        }

Any help is appreciated.

Chid
  • 179
  • 2
  • 2
  • 12
  • 1
    What is the issue with the code you have?? –  Aug 24 '17 at 15:51
  • How is the text file supposed to look like? If your question is about how to write data/strings into a file take a look here: https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java – Piwo Aug 24 '17 at 15:52
  • How do I go about storing the data as there are of different types. Also, Is there a way to make the text file look exactly as the sheet? – Chid Aug 24 '17 at 15:55

1 Answers1

0

As far as I remember there is a getStringValue() method on cells. Maybe you have set the cellformat to string format before reading the string value. After reading the value you can store the rows and cell values in a List < List < String> >. (values) P Than you should find the longest string length. (k)

Call a for cycle inside a for cycle for every value and add extra space for the strings to reach k length. There are writer classes where you can define when to start a new row in the text file.

Zsolt V
  • 517
  • 3
  • 8