在尝试从Java(POI API)设置excel中的cellvalue时,单元格值不会复制到正确的行中

我有两个数组长度不同,想要能够插入数据开始在B3和D3向下,这些是v8columnname和v9columnname。 我也有2个名为v8tableNames和v9tableNames已经填充。 我的数据列表是从两个不同的数据库查询的,我计划在VBA中比较两行,但是我已经创build了这个macros。 因为现在代码中的B列从B3开始,而D列从B行的最后一个索引开始,所以我只能坚持让行alignment。 任何帮助是极大的赞赏

ArrayList v8tableNames = new ArrayList(); ArrayList v9tableNames = new ArrayList(); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet; XSSFRow row; ArrayList v8columns = new ArrayList(); ArrayList v9columns = new ArrayList(); for (int i = 0; i<5; i++) { sheet = workbook.createSheet(); row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Version 8"); row = sheet.getRow(0); cell = row.createCell(2); cell.setCellValue("Version 9"); row = sheet.getRow(0); cell = row.createCell(3); cell.setCellValue(v9tableNames.get(i).toString()); //getv9 is a function that returns column names from v8table v9columns = getv9Columns(v9tableNames.get(i).toString()); row = sheet.getRow(0); //set C1 to v9tablename, one value from the array cell = row.createCell(3); cell.setCellValue(v9tableNames.get(i).toString()); //loop through all table names on v9 to see if there is a match for v8 for (int count = 0; count<v9tableNames.size();count++) { //checks if there is a match in table names if (v9tableNames.get(i).toString().equals(v8tableNames.get(count).toString())) { //puts v8 table name in B1 cell = row.createCell(1); cell.setCellValue(v8tableNames.get(count).toString()); //getv8 is a function that returns table names v8columns = getv8Columns(v8tableNames.get(count).toString()); for (int k = 0; k<v8columns.size() || k<v9columns.size();k++) { //would like to put columnnames from v8table here starting at B3 row = sheet.createRow(k+2); cell = row.createCell(1); cell.setCellValue(v8columns.get(k).toString()); } } } //put v9columns into D3, this is where it gets stuck putting the last value into D(lastindex of B) for (int m = 0; m<v9columns.size();m++) { cell = row.createCell(3); cell.setCellValue(v9columns.get(m).toString()); } } try { FileOutputStream out = new FileOutputStream( new File("Connect.xlsx")); workbook.write(out); out.close(); System.out.println("Workbook.xlsx written successfully" ); } catch(Exception e) { e.printStackTrace(); } 

您需要更新进入v9columns for循环的“行”:

 for (int m = 0; m<v9columns.size();m++) { // Start at row zero and shift to row 3, then increment by m++ on each iteration row = sheet.createRow(0+m+2); cell = row.createCell(3); cell.setCellValue(v9columns.get(m).toString()); } 

另外,我注意到一些冗余使用,'row = sheet.getRow(0);' 在你的代码中,在某些情况下,行已经指向sheet.getRow(0)。 它可以帮助你评论你的代码,你有行/单元格创build/获取,以表明自己哪一列或哪一行正在处理。