如何使用 apache-poi 在列中显示对象

我有一个包含 234 个字段的大 DTO,我必须在使用 apache-poi 创建的 Excel 文件的列中显示此 DTO 的每个字段的值。


这是我的代码:


// Blank workbook

XSSFWorkbook workbook = new XSSFWorkbook();


Sheet sheet = workbook.createSheet("Export values");


// Get the Entity

Simfoot simEntity = simService.findById(simId).get();


Row row = sheet.createRow(0);

row.createCell(1).setCellValue("Consult our values");


// and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).

我想在我的第一列:什么都没有,在我的第二列中只有字符串显示(“咨询我们的价值观”),在我的第三列中我需要有我的 234 个字段。在一个单元格中有一个字段(字段的值)。因此,234 行在第三列中显示一个值。


HUH函数
浏览 178回答 2
2回答

慕尼黑的夜晚无繁华

使用一些反射:    // Blank workbook    XSSFWorkbook workbook = new XSSFWorkbook();    final Sheet sheet = workbook.createSheet("Export values");    // Get the Entity    final Simfoot simEntity = simService.findById(simId).get();    Row row = sheet.createRow(0);    row.createCell(1).setCellValue("Consult our values");    // and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).    Arrays.stream(simEntity.getClass().getDeclaredMethods())            .filter(m -> m.getName().startsWith("get") && m.getParameterTypes().length == 0 && !void.class.equals(m.getReturnType()))            .forEach(m -> {                    try {                            Object value = m.invoke(simEntity, null);                            Row r = sheet.createRow(sheet.getLastRowNum()+1);                            r.createCell(2).setCellValue(value == null ? "" : value.toString());                    }                    catch (Exception ex) {                            // Manage Exception....                    }            });

长风秋雁

我将添加一个方法Simfoot来返回所有值:public List<String> getAllValues() {&nbsp; &nbsp; return Arrays.asList(getAtt1(), getAtt2(), .. , getAtt234());}然后为每个属性创建一行,然后您可以合并前 2 列的行。这里的例子有 6 个属性:int n = 6; // would be 234 for youXSSFCellStyle styleAlignTop = workbook.createCellStyle();styleAlignTop.setVerticalAlignment(VerticalAlignment.TOP);Row row;for(int i=0; i<n; i++) {&nbsp; &nbsp; row = sheet.createRow(i);&nbsp; &nbsp; if(i==0) {&nbsp; &nbsp; &nbsp; &nbsp; Cell cell = row.createCell(1);&nbsp; &nbsp; &nbsp; &nbsp; cell.setCellStyle(styleAlignTop);&nbsp; &nbsp; &nbsp; &nbsp; cell.setCellValue("Consult our values");&nbsp; &nbsp; }&nbsp; &nbsp; row.createCell(2).setCellValue(simEntity.getAllValues().get(i));}sheet.addMergedRegion(new CellRangeAddress(0, n-1, 0, 0));sheet.addMergedRegion(new CellRangeAddress(0, n-1, 1, 1));它显示如下:列出属性的另一种方法是使用反射,但我发现它非常笨拙:Simfoot simEntity = new Simfoot("pap", "pep", "pip", "pop", "pup", "pyp");for(PropertyDescriptor propertyDescriptor :&nbsp; &nbsp; Introspector.getBeanInfo(Simfoot.class).getPropertyDescriptors()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(propertyDescriptor.getReadMethod().invoke(simEntity));}输出:pappeppippoppuppypclass Simfoot所以你必须过滤掉getClass任何其他不需要的方法和吸气剂
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java