news 2026/2/28 17:22:45

Java中导出数据的几种方法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Java中导出数据的几种方法

最近,做了好几个导出的相关功能,用到的方法也不尽相同,因此,这里总结一下各种导出的方法。

先来看下面这个工具类中的export方法

public class CommonUtils{ public static <T> void export (HttpServiceResponse response, Class<T> clazz, String exportFileName, List<T> list, String sheetName){ response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 防止中文乱码 String fileName = URLEncoder.encode(exportFileName, "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Access-Control-Expose-Headers", "content-disposition"); response.setHeader("content-disposition", "attachment;filename="+fileName+".xlsx"); EasyExcel.write(response.getOutputStream(), calzz) .sheet(sheetName) .doWrite(list); } }

再来看看这个使用这个工具类进行导出,使用方法1:

public class BaseService{ @Autowired private Executor taskExecutor; public ResponseEntity<org.springframework.core.io.Resource> exportBusinessInfo(ExportBo exportInfo, HttpServletResponse response) throws IOException{ // 查询导出的数据 List<ExportVO> exportVOList = Mapper.queryExportList(); // 多线程导出 CompletableFuture<?>[] futures = exportVOList.stream().map(exportVO -> // 处理数据,进行格式转换等 CompletableFuture.runAsync(() ->{ exportVO.setProjectName(ConvertUtil.getByCode(exportVO.getProjectCode())); }, taskExecutor) ).toArray(CompletableFuture[]::new);// 将结果转换为CompletableFuture数组 //等待所有任务完成 CompletableFuture.allOf(futures).join(); String exportFileName = "xxxxx"; CommonUtils.export(response, ExportVO.class, exportFileName, exportVOList, "sheetName"); } }

还有这个调用util工具类中export的代码,使用方法2:

public class IndexService{ public void exportIndexAll(IndexBo bo, HttpServletResponse response) throws IOException { String exportFileName = "xxxxx"; List<IndexVo> indexList = mapper.queryAllIndex(bo); CommonUtils.export(reponse, IndexVo.class, exportFileName, indexList, "sheetName"); } }

这里很容易发现,使用方法1是多线程导出,方法2是普通的单线程操作导出。而工具类CommonUtils中使用的是EasyExcel‌进行导出。

来看看,在java中批量导出数据有几种方法分别是怎么使用的有什么优缺点。顺便提一下,本人在开发工作中,使用过的是Apache POI和EasyExcel,以及模板引擎Freemarker。

方法一Apache POI‌适用于Excel文件导出,支持复杂格式设置。需手动管理内存,适合中量级数据。

public void exportData(HttpServletResponse response) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("数据表"); // 创建表头 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("ID"); headerRow.createCell(1).setCellValue("姓名"); headerRow.createCell(2).setCellValue("年龄"); // 创建数据行 List<String[]> dataList = new ArrayList<>(); dataList.add(new String[]{"1", "张三", "25"}); dataList.add(new String[]{"2", "李四", "30"}); dataList.add(new String[]{"3", "王五", "28"}); for (int i = 0; i < dataList.size(); i++) { Row row = sheet.createRow(i + 1); String[] data = dataList.get(i); for (int j = 0; j < data.length; j++) { row.createCell(j).setCellValue(data[j]); } } // 设置响应头 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=data.xlsx"); // 写入输出流 workbook.write(response.getOutputStream()); workbook.close(); }

方法二EasyExcel‌:阿里巴巴开源库,轻量高效,自动分页处理大数据集,避免OOM。适合前端接口导出。

public static void exportData() { String fileName = "exported_data.xlsx"; List<DataModel> dataList = generateData(); EasyExcel.write(fileName, DataModel.class).sheet("Sheet1").doWrite(dataList); log.info("数据导出完成,文件路径:" + fileName); }

方法三JasperReports‌:报表生成工具,支持多种格式(PDF、Excel),适合复杂报表需求

public void exportData(HttpServletResponse response) throws IOException { // 模拟数据源 List<Map<String, Object>> dataList = generateSampleData(); // 编译报表模板(.jrxml) JasperReport jasperReport = JasperCompileManager.compileReport("report_template.jrxml"); // 创建数据源 JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList); // 填充报表 JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource); // 导出为PDF exportToPdf(jasperPrint, "output_report.pdf"); } /** *导出为PDF */ private static void exportToPdf(JasperPrint jasperPrint, String outputPath) throws JRException { Exporter<SimpleExporterInput, SimplePdfExporterConfiguration, SimpleOutputStreamExporterOutput, JRPdfExporter> exporter = new JRPdfExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputPath)); SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration(); exporter.setConfiguration(configuration); exporter.exportReport(); }

需要注意的是,使用JasperReports‌导出数据时,需要配置导出的模板report_template.jrxml,可参考:

<?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report_template" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/> <queryString> <![CDATA[]]> </queryString> <field name="id" class="java.lang.Integer"/> <field name="name" class="java.lang.String"/> <field name="age" class="java.lang.Integer"/> <field name="department" class="java.lang.String"/> <detail> <band height="60"> <textField> <reportElement x="0" y="0" width="100" height="20"/> <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression> </textField> <textField> <reportElement x="100" y="0" width="150" height="20"/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> <textField> <reportElement x="250" y="0" width="100" height="20"/> <textFieldExpression><![CDATA[$F{age}]]></textFieldExpression> </textField> <textField> <reportElement x="350" y="0" width="200" height="20"/> <textFieldExpression><![CDATA[$F{department}]]></textFieldExpression> </textField> </band> </detail> </jasperReport>

方法四CSV导出‌:轻量级文本格式,适合大数据量导出,兼容性好

// 将数据导出为CSV文件 public static void exportToCSV(List<String[]> data, String filePath) throws IOException { FileWriter writer = new FileWriter(filePath); for (String[] row : data) { for (int i = 0; i < row.length; i++) { writer.append(row[i]); if (i < row.length - 1) { writer.append(","); } } writer.append("\n"); } writer.flush(); writer.close(); }

方法五 使用模板引擎(如FreeMarker)

public void export() { // 模拟数据 List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> row1 = new HashMap<>(); row1.put("name", "张三"); row1.put("age", 25); row1.put("city", "北京"); dataList.add(row1); // 配置FreeMarker Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); cfg.setClassForTemplateLoading(ExportDataApp.class, "/templates"); Template template = cfg.getTemplate("export.ftl"); // 输出文件路径 FileWriter writer = new FileWriter("exported_data.html"); template.process(Collections.singletonMap("dataList", dataList), writer); writer.close(); }

最后,再来看一下各种导出方法的的对比分析

Apache POIEasyExcelJasperReports‌CSV模板引擎
优点功能全面,支持复杂格式(如合并单元格、样式)低内存占用,支持大数据量(百万级)‌跨平台兼容性‌、‌数据源支持广泛‌、‌输出格式多样‌、‌模板驱动架构‌、‌与 Java 系统集成‌轻量级,兼容性好‌分离关注点‌、提升开发效率‌、可维护性‌、‌灵活性‌、性能优化‌
缺点内存占用高,大数据量易OOM(Out of Memory)功能相对POI简单(无公式支持)‌模板设计复杂‌、‌数据源配置繁琐‌、‌可视化能力有限‌、社区资源匮乏‌、商业支持有限‌无格式支持‌语法复杂性、集群应用问题‌、‌数据未赋值异常‌、‌静态文件过期风险‌
适用场景小数据量或复杂格式需求大数据量或内存受限环境‌金融行业合规报表‌、‌企业内部系统集成‌、‌数据驱动分析‌纯数据导出或大数据量‌内容管理系统(CMS)、报表生成‌、‌邮件模板‌、配置文件生成‌、‌静态页面预览
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/25 15:53:21

YOLOv8+BiFPN 多尺度目标检测优化全流程指南

文章目录 【研发实战】YOLOv8+BiFPN双向特征金字塔:多尺度检测性能跃升全流程教程 引读:BiFPN为何是你的项目利器? 一、BiFPN核心原理:为什么它能提升多尺度检测? 二、环境准备:快速搭建YOLOv8+BiFPN开发环境 1. 基础依赖安装 三、模块植入:3步将BiFPN嵌入YOLOv8 步骤1:…

作者头像 李华
网站建设 2026/2/26 2:15:57

专业照明厂家的核心能力与行业价值解析

当下照明行业里&#xff0c;专业制造商起着极为关键的作用&#xff0c;它们给各类空间供应基础光环境&#xff0c;还靠着持续的技术创新以及严谨的工艺管控&#xff0c;促使整个产业朝着高效、健康、智能的方向迈进&#xff0c;专业照明产品和普通消费品不一样&#xff0c;它涉…

作者头像 李华
网站建设 2026/2/24 18:41:31

VoiceRun获得550万美元种子轮融资,助力企业语音智能体技术升级

语音AI初创公司VoiceRun日前宣布完成550万美元种子轮融资&#xff0c;该公司专注于帮助企业开发可控的语音智能体。此轮融资由Flybridge Capital Partners领投&#xff0c;RRE Ventures和Link Ventures跟投。VoiceRun表示&#xff0c;这笔资金将主要用于推动市场拓展&#xff0…

作者头像 李华
网站建设 2026/3/1 3:39:29

AI与Python双驱动计量经济学多源数据处理、机器学习预测及复杂因果识别全流程;涵盖数据爬取清洗、因果推断、机器学习、文本分析与可解释AI等

随着数字经济浪潮席卷全球&#xff0c;经济学与管理学的研究范式正面临一场深刻的“数据革命”。传统计量经济学模型虽在因果推断上根基扎实&#xff0c;但面对海量、高维、非结构化的文本、图像数据时&#xff0c;常显得力不从心&#xff1b;而以机器学习、深度学习为代表的前…

作者头像 李华
网站建设 2026/3/1 3:09:25

Sumsub 年度欺诈报告重磅发布!AI 智能体诈骗 2026 年或全面爆发

未来的验证系统不仅需要确认你是谁&#xff0c;还需要确认操作背后是真实用户还是AI智能体。 Sumsub最新发布的《2025-2026年身份欺诈报告》中表明&#xff1a;全球身份欺诈率整体看似趋于稳定&#xff0c;但高质量攻击在过去一年间激增了180%。 该报告分析了数百万次验证检查和…

作者头像 李华