簡體   English   中英

嘗試從Excel中獲取數據,然后將其存儲在數組中,然后再打印

[英]Trying to get data from excel then store it inside array and later print it

我正在嘗試從Excel文件中讀取數據。 當我運行下面的代碼時,它可以正常運行,但不會提供任何數據。 當我檢查代碼時,我發現全局變量rownum尚未初始化並給出默認值0。但是在getData(int i)方法中,rownum給出的值為14。我試圖獲取所有字符串數據通過使用getData(int i)方法在excel文件中可用,然后嘗試將它們存儲在data []數組中。 再次在setData方法內,我試圖將存儲在data []數組內的所有項目復制到字符串值。 誰能幫忙。 我是Java新手。 包com.selenium;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;


@SuppressWarnings("unused")
public class DataFromExcel {
  String[] data = new String[15];
  static int rownum;

 public String[] getData(int i) throws InvalidFormatException, IOException{
   File file = new File("C:\\Users\\Admin\\Desktop\\ScreenShot\\Excel.xls");
   FileInputStream input = new FileInputStream(file);
   Workbook excel = WorkbookFactory.create(input);
   Sheet sheet = excel.getSheet("Data");
   rownum = sheet.getLastRowNum();
   System.out.println(rownum);


     for(int j=1;j<=rownum;j++){
         Row row = sheet.getRow(rownum);
         while(row != null){
         if(row.getCell(j) != null){
         String cell = row.getCell(j).getStringCellValue();
         while(cell != null){
             data[j]=cell;
             System.out.println(data[1]);
         }//while cell
        }//if row 
      }//for  
     }//row while
    return data;
   }//getData 
  public String setData(int i){
      String value = null;
      for(i=1; i<=data.length;i++){
          value =data[i];
      }//for setData
    return value;
  }//setData

 public static void main(String[] args) throws InvalidFormatException, IOException{
    DataFromExcel get = new DataFromExcel();
    System.out.println(rownum);
    get.getData(1);
    if(get.data != null){
    System.out.println(get.setData(1));}
 }//main
}// DataFromExcel

您已經知道(我期望如此) ,該程序的執行是從main()方法開始的。現在,當您調用getData(int i)方法時,此時rownum為零(顯然沒有代碼在修改。它),但隨后您調用了帶有參數的getData(int i) ,該參數隨后根據其中的指令更改了rownum的值,請嘗試添加另一個System.out.prinltn()作為main()方法的結束行並打印rownum.的值rownum.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM