我目前正致力于导入Excel工作表数据,将数据行存储在数组中。我的目标是将每个单元格数据存储在一个唯一定义的变量中,并同时使用相同的变量进行单次迭代,同时保存下一个数据在同一个变量中行并重用。任何人都可以在这个问题上帮助我(请解释一个例子只是为了理解) 这是代码的方式
public static void main(String[] args)throws NullPointerException {
try {
File fXmlFile = new File("bin/testngscript/v1.xml");
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
Document doc = db.parse(fXmlFile);
//read the xml node element
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Excelpath");
String excelpath1 =null;
for (int index = 0; index < nodeList.getLength(); index++) {
System.out.println(nodeList.item(index).getTextContent());
excelpath1= nodeList.item(index).getTextContent();
System.out.println(excelpath1);
}
excelpath2= excelpath1;
System.out.println(excelpath2);
}
catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
int rownum = 0;
String Filepath = excelpath2;
FileInputStream file = new FileInputStream(Filepath);
@SuppressWarnings("resource")
HSSFWorkbook hw = new HSSFWorkbook(file);
HSSFSheet sheet = hw.getSheetAt(0);
rownum= sheet.getLastRowNum();
Object[][] product_data=new Object[rownum][14];
try {
System.out.println("excelpath is"+excelpath2);
for(int i=1;i<rownum;i++){
for(int j=0;j<14;){
product_data[i][j]="productname";
product_data[i][j++]="url";
product_data[i][j++]="themename";
product_data[i][j++]="papertype";
product_data[i][j++]="paperfinish";
product_data[i][j++]="packaging";
product_data[i][j++]="noofpages";
product_data[i][j++]="expectedprice";
product_data[i][j++]="priceinkart";
product_data[i][j++]="shippingcharges";
product_data[i][j++]="taxexpected";
product_data[i][j++]="taxactual";
product_data[i][j++]="total";
product_data[i][j++]="totalexpected";
System.out.println(product_data[i][j++]);
j=0;
}
}
}
catch(Exception e){
e.printStackTrace();
}
答案 0 :(得分:0)
这可能是一个间接的答案,使用java反射从xls获取数据更容易做到。 以testng或selenium为例,他们以同样的方式做几件事
实施例 A library that can fill Java object with data declared in Excel file http://persistentdesigns.com/wp/2010/02/excel-read-writable-reports-through-generics-reflection-and-apache-poi/
github中的好例子