将数据库查询的信息导出到Excel

将数据库查询的信息导出到Excel

生成Excel及数据
public class ExportExcel<T> {
        /**
     * Excel导出功能
     * 注意:T类字段名和containBean集合里字段名字的一致性
     *
     * @param title       表名
     * @param headers     表头
     * @param list        要生成的数据
     * @param containBean 选择要生成的字段(可选)
     * @throws Exception
     */
    public void exportExcel(String title, String[] headers, Collection<T> list, 			List<String> containBean, OutputStream out) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFCellStyle style = getHssfCellStyleOne(workbook);
        HSSFSheet sheet = getHSSFSheet(title, headers, workbook, style);
        HSSFCellStyle style2 = getHssfCellStyleTwo(workbook);
        getRows(headers, style, sheet);
        HSSFRow row;
        try {
            Iterator<T> it = list.iterator();
            int index = 1;
            //下面两行设置字体,一定要写到循环外面,否则在大量数据的情况下,后面的数据无法写入报错
            HSSFFont font3 = workbook.createFont();
            font3.setColor(HSSFColor.BLUE.index);
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                T t = (T) it.next();
                // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
                Field[] fields = t.getClass().getDeclaredFields();
                /*如果需要匹配*/
                if (CollectionUtils.isNotEmpty(containBean)) {
                    for (int j = 0; j < containBean.size(); j++) {
                        for (int i = 0; i < fields.length; i++) {
                            Field field = fields[i];
                            if (!field.getName().equals(containBean.get(j)))
                                continue;
                            /*给每一列set值*/
                            setCellValue(style2, t, field, row, j, font3);
                        }
                    }
                } else {
                    for (int i = 0; i < fields.length; i++) {
                        Field field = fields[i];
                        setCellValue(style2, t, field, row, i, font3);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("写数据到excel失败,title" + title, e);
        } finally {
            // 清理资源
        }
        try {
            //关闭excel读写流
            workbook.write(out);
        } catch (IOException e) {
            logger.error("导出文件失败", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("关闭流失败", e);
                }
            }
        }
    }
}
将数据写入到Excel
public void writeExcel(String excelName, String[] headers, Collection<T> list, List<String> containBean, HttpServletResponse response) {
        try {
            String codedFileName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            OutputStream os = response.getOutputStream();
            exportExcel(excelName, headers, list, containBean, os);
            os.flush();
            //关闭response的输出流
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
生成Excel和一种字体
private HSSFCellStyle getHssfCellStyleOne(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }
生成Excel表及表头数据
private HSSFSheet getHSSFSheet(String title, String[] headers, HSSFWorkbook workbook, HSSFCellStyle style) {
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 产生表格大标题行 ( 起始行,起始列,结束行,结束列)
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) (headers.length - 1)));
        HSSFRow rowTitle = sheet.createRow(0);
        HSSFCell cellTitle = rowTitle.createCell(0);
        cellTitle.setCellStyle(style);
        HSSFRichTextString textTitle = new HSSFRichTextString(title);
        cellTitle.setCellValue(textTitle);
        return sheet;
    }
生成字体
private HSSFCellStyle getHssfCellStyleTwo(HSSFWorkbook workbook) {
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        return style2;
    }
生成表格标题行
private HSSFRow getRows(String[] headers, HSSFCellStyle style, HSSFSheet sheet) {
        // 产生表格标题行
        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        return row;
    }
设置每一行中的列
private void setCellValue(HSSFCellStyle style2, T t, Field field, HSSFRow row, int index, HSSFFont font3) {
        HSSFCell cell = row.createCell(index);
        cell.setCellStyle(style2);
        Object value = invoke(t, field);
        String textValue = null;
        if (value != null) {
            if (value instanceof Date) {
                Date date = (Date) value;
                textValue = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
            } else {
                // 其它数据类型都当作字符串简单处理
                textValue = value == null ? "" : value.toString();
            }
        }
        if (textValue != null) {
            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
            Matcher matcher = p.matcher(textValue);
            if (matcher.matches()) {
                cell.setCellValue(Double.parseDouble(textValue));
            } else {
                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                richString.applyFont(font3);
                cell.setCellValue(richString);
            }
        }
    }
反射映射数据集字段
private Object invoke(T t, Field field) {
        try {
            String fieldName = field.getName();
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, t.getClass());
            Method method = pd.getReadMethod();
            return method.invoke(t);
        } catch (Exception e) {
            return null;
        }
    }
使用实例
ExportExcel<要导出的类> exportExcel = new ExportExcel<>();
String[] headers = new String[]{"Excel的表头1", "Excel的表头2", "Excel的表头3", "Excel的表头4"};
List<String> beans = Arrays.asList("要导出的类的字段", "位置和上面对应", "一一对应", "字段"); //如果需要全部导出,则不需要写beans,下面把beans置为null即可
exportExcel.writeExcel("给Excel取个名字", headers, list, beans, response);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值