How do I modify the code so it only prints cells E

2019-07-22 08:40发布

I wrote a small program on java to read a excel, but how do I modify it so it only prints certain cells?

public class Read
{
    public static void main(String [] args) throws Exception
    {
        File f = new File ("/users/Me/Documents/Test.xls");
        Workbook wb = Workbook.getWorkbook(f);
        Sheet s = wb.getSheet(0);
        int row = s.getRows();
        int col = s.getColumns();

        for(int i = 0; i<row;i++)
        {
            for(int j = 0; j<col;j++)
            {
                Cell c = s.getCell(j,i);
                System.out.print(c.getContents()+"\t");
            }
        }

        System.out.println("");
    }

}

标签: java excel
2条回答
再贱就再见
2楼-- · 2019-07-22 09:16

If you mean that you want to print only specific cells out of all then may be you can write a method specifying your condition and if a cell meets it then only print it else continue.

public class Read {
 public static void main(String [] args) throws Exception{
    File f = new File ("/users/Me/Documents/Test.xls");
    Workbook wb = Workbook.getWorkbook(f);
    Sheet s = wb.getSheet(0);
    int row = s.getRows();
    int col = s.getColumns();
    for(int i = 0; i<row;i++)
    for(int j = 0; j<col;j++){
        Cell c = s.getCell(j,i);
        if(!doesCellMeetMyCondition(c))
          continue;
        System.out.print(c.getContents()+"\t");
    }
    System.out.println("");
 }
 private boolean doesCellMeetMyCondition(Cell c) {
   // Check your condition and return true or false.
 }
}
查看更多
叛逆
3楼-- · 2019-07-22 09:22

If you want to print every 'E' cell then you would want to remove the column loop but keep the row loop and hardcode the index of 'E' into the getCell(x,y) function. As we know 'E' is index 4 in the alphabet therefor if we use the code,

public static void main(String [] args) throws Exception{
    File f = new File ("/users/Me/Documents/Test.xls");
    Workbook wb = Workbook.getWorkbook(f);
    Sheet s = wb.getSheet(0);
    int row = s.getRows();
    int col = s.getColumns();
    for(int i = 0; i<row;i++){
            Cell c = s.getCell(4,i);
            System.out.print(c.getContents()+"\t");
        }
    System.out.println("");
}

Only columns in the 'E' column will be printed.

For your follow up question, how to check if the contents of one cell is greater than the other... Your main problem here is that you are comparing two strings, in order to check if one value is greater than the other you must parse the string to an int (or other data type). In java this can be done by casting or by using methods given to us by datatype functions. An example is seen below where we compare cells C1 and E1.

    Cell c = s.getCell(2,1);
    Cell e = s.getCell(4,1);
    if(Integer.parseInt(c.getContents()) > Integer.parseInt(e.getContents())){
        //Do something
    }
查看更多
登录 后发表回答