我有2个数组,它们的长度各不相同,并且希望能够插入从B3和D3向下开始的数据,它们是v8columnname和v9columnname。我也有两个已经填充的称为v8tableNames和v9tableNames。我的数组列表是从两个不同的数据库查询的,我计划比较VBA中的两行,但是我已经设置了该宏。我只是坚持让行完美对齐,因为代码现在B列从B3开始,而D列从B行的最后一个索引开始。任何帮助是极大的赞赏
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 (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)。它可以帮助您注释您创建/获取行/单元格的代码,以向自己指示要寻址的是哪一列或哪一行。