Java读数据库并将数据写入到Excel中

1.Java创建Excel的表头

 public static void createSheet(Workbook workbook, String sheetName, String[] columnTitles) {
        Sheet sheet = workbook.createSheet(sheetName);
        Row headerRow = sheet.createRow(0);

        // 设置表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        //设置字体大小
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerStyle.setFont(headerFont);
        // 设置表头边框样式
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        // 设置自动换行
        headerStyle.setWrapText(true);
        // 设置对齐方式
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置背景颜色
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 创建表头
        for (int i = 0; i < columnTitles.length; i++) {
            sheet.autoSizeColumn(i);
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columnTitles[i]);
            cell.setCellStyle(headerStyle);
        }
        sheet.getRow(0).setHeightInPoints(70);
    }

2.Java将数据写入到Excel中

public <T> void processGatherData(Workbook workbook, List<T> gatherList, String sheetName, String[] columnTitles) throws IllegalAccessException, NoSuchFieldException {
        ExcelUtil.createSheet(workbook, sheetName, columnTitles);
        Sheet sheet = workbook.getSheetAt(0);
        if (gatherList != null && !gatherList.isEmpty()) {

            for (int rowIndex = 0; rowIndex < gatherList.size(); rowIndex++) {
                Row dataRow = sheet.createRow(rowIndex + 1);
                T gatherData = gatherList.get(rowIndex);
                int count = 0;
                Field[] fields = gatherData.getClass().getDeclaredFields();

                for (Field field : fields) {
                    field.setAccessible(true);
                  
                    try {
                        Cell cell = dataRow.createCell(count++);
                        Object fieldValue = field.get(gatherData);
                        ExcelUtil.setCellValue(cell, fieldValue);
                    } catch (IllegalAccessException e) {
                        log.error("处理数据出错:" + e.getClass().getSimpleName() + " - " + e.getMessage());
                    }
                }
            }
        }
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值