Java. HSSF. Apache-poi. How to modificate code

前端 未结 3 1560
無奈伤痛
無奈伤痛 2021-01-26 04:06

My data is stored in a format(look down): [-] means a blank cell, on the right may be only 10 columns, after the space. Something like this:
[string0]

3条回答
  •  执念已碎
    2021-01-26 04:47

    External Link: Busy Developers' Guide to HSSF and XSSF Features

    Here is an example that should work.

    Maven Dependencies:

    
        org.apache.poi
        poi
        3.9
    
    
        org.apache.poi
        poi-ooxml
        3.9
    
    

    Code:

    import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.*;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Iterator;
    
    public class StackOverflowQuestion18095443 {
    
        public static void main(String[] args) {
            if(args.length != 1) {
                System.out.println("Please specify the file name as a parameter");
                System.exit(-1);
            }
            String sfilename = args[0];
            File file = new File("C:\\Users\\student3\\" + sfilename + ".xls");
            read(file);
        }
    
        public static void read(File file) {
            try (InputStream in = new FileInputStream(file)) {
                HSSFDataFormatter formatter = new HSSFDataFormatter();
                Workbook workbook = WorkbookFactory.create(in);
                Sheet sheet = workbook.getSheetAt(0);
                Iterator rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    StringBuilder rowText = new StringBuilder();
                    Iterator cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        String cellAsStringValue = formatter.formatCellValue(cell);
                        rowText.append(cellAsStringValue).append(" ");
                    }
                    System.out.println(rowText.toString().trim());
                }
            } catch (InvalidFormatException | IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    As for terminating the iteration you can conditionally break from the loop. Or, you could also just not use an iterator. Notice that you can obtain a Cell from a Row using a named reference (this allows you to refer to a cell by name, such as "A2", just like you would in Excel) or simply by the column index within the row.

提交回复
热议问题