【发布时间】:2014-09-23 19:57:22
【问题描述】:
我正在尝试从 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
【问题讨论】:
标签: java arrays excel for-loop