POI报表导出

本文介绍如何利用Apache POI库实现Java程序批量导出Excel文件的功能。具体包括Maven依赖配置、模板读取、样式设置、数据填充等关键步骤,并解决了文件名中空格显示为加号的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在实际项目中会遇到一些报表导出功能的开发,接下来废话不多说,直接把我在项目中用到的分享给大家

一:pom.xml导入依赖

        <!-- excel poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.9.1</version>
        </dependency>

二:核心代码

	InputStream inputStream = null;
		try {
			inputStream = ProductController.class.getClassLoader()
					.getResourceAsStream("templet/report/productInformation.xlsx");模板路径
		} catch (Exception e) {
			logger.error("-----------读取模板失败-------------");
		}
		XSSFWorkbook wb = new XSSFWorkbook(inputStream);
		XSSFSheet sheet0 = wb.getSheetAt(0);//获取第一个单元格
		XSSFCellStyle cstyle = wb.createCellStyle(); // 样式对象
		// 设置边框
		cstyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
		cstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		cstyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
		cstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
		XSSFFont font1 = wb.createFont();
		font1.setFontHeightInPoints((short) 10);
		font1.setFontName("Calibri");
		cstyle.setFont(font1);
		cstyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		cstyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
	   // 数据处理
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		XSSFRow row = null;
		XSSFCell cell = null;

		// 货品列表
		Page showPage = new Page(0, 500);
		logger.info(URLDecoder.decode(productName, "UTF-8"));
		List<ProductOutputInfo> productList = this.productService.queryProductListByParems(showPage, URLDecoder.decode(productName, "UTF-8"), productDesc, productId);//实际项目中需要的数据列表
		if(null != productList && productList.size()>0){
           //单独封装一个方法用于进行单元格cell填充内容
			SetProductExcel(productList, sheet0, cstyle, row, cell, formatter);
			// 末尾
			String tempFileName = "productInformation.xlsx";
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(tempFileName, "utf-8"));
			OutputStream outputStream = response.getOutputStream();
			try {
				wb.write(outputStream);
			} catch (Exception e) {
				// TODO: handle exception
			} finally {
				outputStream.flush();
				outputStream.close();
			}

三:填充数据方法代码:

private void SetProductExcel(List<ProductOutputInfo> records, XSSFSheet sheet, XSSFCellStyle cstyle, XSSFRow row,
			XSSFCell cell, SimpleDateFormat formatter) {

		if (records != null && records.size() > 0) {
			int rowInt = 0; //从sheet表的第一行开始,第一行为0;
			for (int i = 0; i < records.size(); i++) {
				rowInt = i + 1; //代表第二行
				row = sheet.createRow(rowInt);
				// update_time
				int j = 0; //单元cell从0开始
				cell = row.createCell(j++);
				cell.setCellValue(null==records.get(i).getUpdateDate()?"":records.get(i).getUpdateDate());
				cell.setCellStyle(cstyle);
				//sap_code
				cell = row.createCell(j++);
				cell.setCellValue(null==records.get(i).getSapCode()?"":records.get(i).getSapCode());
				cell.setCellStyle(cstyle);
				//MH...需要填充的字段
			
			}
		}
	}

补充:实际中可能出现导出excel名带空格,导出的为+号连接,解决这个用:
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
		String dateFt = ft.format(Calendar.getInstance().getTime());
		// 末尾
		String tempFileName = "Bottles Collection - Active Users List v" + dateFt + ".xlsx";
		response.setContentType("application/vnd.ms-excel");
		// replace("\\+","%20") 解决空格变成"+"的bug
		String filename = URLEncoder.encode(tempFileName, "utf-8").replace("+", "%20");
		response.setHeader("Content-Disposition", "attachment; filename=" + filename);
		OutputStream outputStream = response.getOutputStream();

 

亲测有效.

 

 

安装Docker安装插件,可以按照以下步骤进行操作: 1. 首先,安装Docker。可以按照官方文档提供的步骤进行安装,或者使用适合您操作系统的包管理器进行安装。 2. 安装Docker Compose插件。可以使用以下方法安装: 2.1 下载指定版本的docker-compose文件: curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose 2.2 赋予docker-compose文件执行权限: chmod +x /usr/local/bin/docker-compose 2.3 验证安装是否成功: docker-compose --version 3. 在安装插件之前,可以测试端口是否已被占用,以避免编排过程中出错。可以使用以下命令安装netstat并查看端口号是否被占用: yum -y install net-tools netstat -npl | grep 3306 现在,您已经安装Docker安装Docker Compose插件,可以继续进行其他操作,例如上传docker-compose.yml文件到服务器,并在服务器上安装MySQL容器。可以参考Docker的官方文档或其他资源来了解如何使用DockerDocker Compose进行容器的安装和配置。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Docker安装docker-compose插件](https://blog.csdn.net/qq_50661854/article/details/124453329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Docker安装MySQL docker安装mysql 完整详细教程](https://blog.csdn.net/qq_40739917/article/details/130891879)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值