Home > Back-end >  transferring data read from excel to array
transferring data read from excel to array

Time:03-22

I want to transfer this data to an array to perform mathematical operations with the data I read from excel. how can I do that?

    import java.io.IOException;
    import jxl.Cell;
    import jxl.Sheet;
    import jxl.Workbook;
    import  jxl.read.biff.BiffException;
    import jxl.write.*;
    import jxl.write.Number;

public class SimMod {
    public static void main(String[] args) throws Exception {
        File f=new File("C:\\Users\\data.xls");
        Workbook Wb=Workbook.getWorkbook(f);
        Sheet sh=Wb.getSheet(0);
        int [] mathArray=new int[48];
        int row=sh.getRows();
        int col= sh.getColumns();
        for (int i=0;i<row;i  ){
            for (int j=0;j<col;j  ){
                Cell c=sh.getCell(j,i);
                System.out.print(c.getContents());
            }
            System.out.println("   ");
        }
    }
} 

CodePudding user response:

Don't use a dynamic array. Use an ArrayList instead. Change int [] mathArray=new int[48] to ArrayList<Integer> mathArray = new ArrayList<>();

Then add the line mathArray.add(c.getContents()) after or before the line System.out.print(c.getContents());

Edit: If you want to have separate rows and columns, you can do this instead:

public static void main(String[] args) throws Exception {
    File f=new File("C:\\Users\\data.xls");
    Workbook Wb=Workbook.getWorkbook(f);
    Sheet sh=Wb.getSheet(0);
    ArrayList<ArrayList<Integer>> mathArray=new ArrayList<>();
    int row=sh.getRows();
    int col= sh.getColumns();
    for (int i=0;i<row;i  ){
        ArrayList<Integer> colArr = new ArrayList<>();
        for (int j=0;j<col;j  ){
            Cell c=sh.getCell(j,i);
            colArr.add(c.getContents());
        }
        mathArray.add(colArr);
    }
}

Now you can access the element in row i and column j with mathArray.get(i).get(j)

  • Related