2
\$\begingroup\$

I'm working with Apache POI framework.

This code go through sheets, row and get value of cells. I will try to get value from directly indicated column. I need this because I want convert only some information from xls to csv.

FileOutputStream fos = new FileOutputStream(outputFile);

Workbook workbook = null;
for (File input : inputFile) {
  String ext = FilenameUtils.getExtension(input.toString());

  if (ext.equalsIgnoreCase("xlsx")) {
    workbook = new XSSFWorkbook(new FileInputStream(input));
  } else if (ext.equalsIgnoreCase("xls")) {
    workbook = new HSSFWorkbook(new FileInputStream(input));
  }

  int numberOfSheets = workbook.getNumberOfSheets();
  Row row;
  Cell cell;
  Sheet sheet = null;
  int[] kolumny = {1, 2, 3, 4, 5, 6, 7, 50, 51, 52, 53, 54, 55};

  for (int i = 1; i < numberOfSheets; i++) {
    sheet = workbook.getSheetAt(i);
    if (sheet.getLastRowNum() > 24) {
      Iterator<Row> rowIterator = sheet.iterator();
      while (rowIterator.hasNext()) {
        row = rowIterator.next();
        for (int j = 23; j < sheet.getLastRowNum(); j++) {
          if (row.getRowNum() == j) {
            if (row.getCell(1) == null || row.getCell(1).getCellType() == Cell.CELL_TYPE_BLANK) {
              break;
            }
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
              cell = cellIterator.next();
              for (int kolumna : kolumny) {
                if (cell.getColumnIndex() == kolumna) {
                  if (cell != null) {
                    switch (cell.getCellType()) {
                      case Cell.CELL_TYPE_BOOLEAN:
                        data.append(cell.getBooleanCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_NUMERIC:
                        data.append(cell.getNumericCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_STRING:
                        data.append(cell.getStringCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_BLANK:
                        data.append("" + ",");
                        break;
                      default:
                        data.append(cell + ",");
                    }
                  }
                }
              }
            }
            data.append('\n');
          }
        }
      }
    }
  }
}
\$\endgroup\$
5
  • 2
    \$\begingroup\$ Please describe the intended purpose of this code, and also make a title that isn't generic. See How to Ask. \$\endgroup\$ Commented Feb 18, 2016 at 9:04
  • \$\begingroup\$ Ok i will edit my question. \$\endgroup\$ Commented Feb 18, 2016 at 9:41
  • 1
    \$\begingroup\$ The new title is no more informative or distinct. \$\endgroup\$ Commented Feb 18, 2016 at 9:54
  • \$\begingroup\$ You seem to be missing some of your imports - where do Workbook, XSSFWorkbook and the rest come from? \$\endgroup\$ Commented Nov 7, 2018 at 11:40
  • \$\begingroup\$ where is data declared ? \$\endgroup\$
    – theRiley
    Commented Jan 7, 2021 at 21:57

4 Answers 4

2
\$\begingroup\$

You could extract the content of inner loops to methods with speaking names.

E.g. You could introduce a method like

public static void processSheet(Sheet sheet)
{
  if (sheet.getLastRowNum() > 24) {
      Iterator<Row> rowIterator = sheet.iterator();
      while (rowIterator.hasNext()) {
        row = rowIterator.next();
  ...  

}

Within this method you can extract another method e.g.

public static void processRow(Row row){
  for (int j = 23; j < sheet.getLastRowNum(); j++) {
    if (row.getRowNum() == j) {
      if (row.getCell(1) == null || row.getCell(1).getCellType() == Cell.CELL_TYPE_BLANK) {
        break;
    ...       

}

And so on until you have only short methods with speaking names. This makes the code easier to read and understand.

\$\endgroup\$
0
2
\$\begingroup\$

Try using

 workbook = WorkbookFactory.create();

instead of

String ext = FilenameUtils.getExtension(input.toString());

  if (ext.equalsIgnoreCase("xlsx")) {
    workbook = new XSSFWorkbook(new FileInputStream(input));
  } else if (ext.equalsIgnoreCase("xls")) {
    workbook = new HSSFWorkbook(new FileInputStream(input));
  }

WorkbookFactory is used for creating the appropriate kind of Workbook (be it HSSFWorkbook or XSSFWorkbook), by auto-detecting from the supplied input.

Reference

Another suggestion is to change possible loops into smaller methods like this answer.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thank you i use MrSmith42 metod but also i used your tip. \$\endgroup\$ Commented Feb 18, 2016 at 13:59
-1
\$\begingroup\$

You can try to use this jar library:

https://afajardomorera.github.io/ExcelReader/

You can define a Java Object with the fields you need, configure a property file (where you can define concrete cells to extract and/or data rows from a table to extract) and invoke the reader method from the jar.

In the github code, you find a jar_generated folder with the latest version of the jar to use it.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ That sounds more like a product recommendation than a review. That's not the purpose of Code Review - see the Help Centre for more guidance on writing on-topic answers. \$\endgroup\$ Commented Nov 7, 2018 at 10:33
  • \$\begingroup\$ @TobySpeight Using an existing library to do the job sounds to me like a valid review. "Don't reimplement the wheel" and all that. \$\endgroup\$ Commented Nov 7, 2018 at 11:26
  • \$\begingroup\$ @Simon - possibly, but there should at least be some explanation of why that library could be a better choice in this context than the one currently used by the code. (A better recommendation would also summarize the license terms, so that OP can quickly decide whether it's even worth looking at). \$\endgroup\$ Commented Nov 7, 2018 at 11:42
-1
\$\begingroup\$

I added the answer with the link recommendation to a jar:

https://afajardomorera.github.io/ExcelReader/

Last tuesday, I finished the development of the 0.0.1 version of that library.

Is an application where you can read and extract the information of an excel file and set the values to the java objects you define for it.

To do this, you have to create a property file with the configuration needed (explained in the url)... basically, you can set the sheet indexs to process, what binding class for each sheet, if you want.. what binding class for data rows (will be a list field of that type into the sheet binding class), complete cell reference to process specific cells... and the name and type of variable to binding the cell values, that have to be fields with the same name and type into binding classes.

To summarize... you only have to add jar into your app, define de property file and the binding classes (depends on the data you want to process in the excel file) and only have to invoke the ExcelReader.reader method with params: Excel File, Map and ResourceBoundle...

Map: Key is the SimpleName of the class. Value is an instance of the object (new TableDTO(), for example) ResourceBoundle: is the property file loaded into a ResourceBoundle

The reader method return a Map where Key is the sheet index and value is a List of the Objects you have defined with the information of the excel inside.

Is my first time in this web. If here only post code... I take note about that for next posts.

Thank you.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to Code Review. This site is slightly different than Stack Overflow. From the Help Center page How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted. In addition to criticisms, pointing out good practices in the code is also a form of helpful feedback." \$\endgroup\$ Commented Nov 8, 2018 at 15:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.