我想读取excel表值并将这些值存储在Java中的数组中.
我已准备好读取excel表的代码,但我无法自定义它以将这些值存储在Array中.
这是我阅读excel表的代码:
package com.core.testscripts;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class NewExcel
{
private String inputFile;
public void setInputFile(String inputFile)
{
this.inputFile = inputFile;
}
public void read() throws IOException
{
File inputWorkbook = new File(inputFile);
Workbook w;
try
{
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++)
{
for (int i = 0; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
System.out.println(cell.getContents());
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException
{
NewExcel test = new NewExcel();
test.setInputFile("D:/hellohowareyou.xls");
test.read();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您确实想要一个数组,则在为其分配存储空间时必须知道数组中需要多少个元素。您可以在运行时执行此操作(不必在编译时知道),但必须在使用该数组之前执行此操作。
在声明部分的某处:
String[] dataArray = null;
Run Code Online (Sandbox Code Playgroud)
然后在代码中的某个地方
dataArray = new String[numberOfElements];
Run Code Online (Sandbox Code Playgroud)
您可以按照相同的原理创建二维(或更多)维数组。之后,您可以将字符串分配给数组中索引小于的任何元素numberOfElements。