From 887ec2084a32aec3dfdfd2ef5bcd1c9c92efb3a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=B1=E6=B6=9B?= <15850646081@163.com> Date: Tue, 23 Jan 2024 14:06:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=BC=E5=87=BAexcel=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../engine/salary/util/excel/ExcelUtil.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/com/engine/salary/util/excel/ExcelUtil.java b/src/com/engine/salary/util/excel/ExcelUtil.java index 877714295..2a482e42d 100644 --- a/src/com/engine/salary/util/excel/ExcelUtil.java +++ b/src/com/engine/salary/util/excel/ExcelUtil.java @@ -1,7 +1,9 @@ package com.engine.salary.util.excel; +import com.engine.salary.entity.taxdeclaration.dto.TaxDeclarationLaborListDTO; import com.engine.salary.util.SalaryDateUtil; import com.engine.salary.util.SalaryI18nUtil; +import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.FillPatternType; @@ -10,7 +12,12 @@ import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.xssf.usermodel.*; import java.awt.*; +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -69,6 +76,41 @@ public class ExcelUtil { return workbook; } + public static XSSFWorkbook genWorkbook(String sheetName, List rowList) { + List headerList = Lists.newArrayList(); + List dataIndexList = Lists.newArrayList(); + // 解析表头 + ExcelUtil.parseHeader(TaxDeclarationLaborListDTO.class, headerList, dataIndexList); + + List> rows = new ArrayList<>(); + rows.add(headerList); + for (int i = 0; i < rowList.size(); i++) { + List row = Lists.newArrayListWithExpectedSize(dataIndexList.size()); + for (int j = 0; j < dataIndexList.size(); j++) { + Object value = getValue(rowList.get(i), dataIndexList.get(j)); + row.add(value); + } + rows.add(row); + } + return genWorkbookV2(rows, sheetName); + } + + private static Object getValue(T t, String fieldName) { + Object value = null; + try { + BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass()); + PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor property : props) { + if (fieldName.equals(property.getName())) { + Method method = property.getReadMethod(); + value = method.invoke(t, new Object[]{}); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return value; + } public static XSSFWorkbook genWorkbookV2(List> rowList, String sheetName) { XSSFWorkbook workbook = new XSSFWorkbook();