JAVA 使用 POI 导出 EXCEL 自定义背景颜色

巧了我就是萌 提交于 2019-12-25 16:30:46

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

开发中导入和导出 excel 是常见的功能,在这里记录下使用 POI 导出表格的简单实现,下一篇在分享下导入表格,话不多说直接上代码。

1、项目引入 maven 依赖

		<!-- poi -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>

2、导出表格数据接口

	@RequestMapping("/exportTemplate")
	public void exportDelayTemplate(HttpServletResponse response) {
		String fileLocation = HttpRequestUtil.getHttpRequest().getServletContext().getRealPath("download");
		File file = new File(fileLocation);
		if (!file.exists()) {
			file.mkdirs();
		}
		String fileName = System.currentTimeMillis() + StringUtil.getRandomString() + ".xls";
		// 创建excel文件对象
		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建excel的表单对象
		HSSFSheet sheet = wb.createSheet("创建Excel模板");
		// 在相应的单元格进行赋值
		try {
			// 创建excel的行对象
			HSSFRow row = sheet.createRow((int) 0);
			// 设置单元格样式
			HSSFCellStyle style = wb.createCellStyle();
			style.setFillForegroundColor(IndexedColors.RED.getIndex());
			style.setFillPattern(CellStyle.SOLID_FOREGROUND);
			// 用行对象得到Cell对象
			HSSFCell cell = row.createCell(0);
			cell.setCellValue("姓名");
			cell.setCellStyle(style);
			cell = row.createCell(1);
			cell.setCellValue("手机号");
			cell.setCellStyle(style);
			cell = row.createCell(2);
			cell.setCellValue("年龄");
			cell.setCellStyle(style);
			// 循环将数据写入Excel
			List<String> list = new ArrayList<>();
			// 测试数据,这里可以根据自己业务封装数据对象
			list.add("test1");
			list.add("test2");
			list.add("test3");
			for (int i = 0; i < list.size(); i++) {
				// 创建单元格,设置值
				row = sheet.createRow((int) i + 1);
				String string = list.get(i);
				HSSFCell createCell = row.createCell(0);
				createCell.setCellValue(string);
				// 设置颜色
				createCell.setCellStyle(style);
				row.createCell(1).setCellValue(string);
				row.createCell(2).setCellValue(string);
			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			wb.write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// Excel路径
			String excel = fileLocation + File.separator + fileName;
			File fi = new File(excel);
			if (!fi.exists()) {
				fi.createNewFile();
			}
			FileUtils.copyInputStreamToFile(is, fi);
			// 输出Excel文件
			File f = ResourceUtils.getFile(fileLocation + File.separator + fileName);
			// 设置响应头
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + ExcelUtils.toUtf8String("Excel模板") + ".xls");
			ServletOutputStream out = response.getOutputStream();
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(new FileInputStream(f));
				bos = new BufferedOutputStream(out);
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				throw e;
			} finally {
				if (wb != null) {
					wb.close();
				}
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

3、导出效果如下图

以上就是使用 POI 导出 Excel 表格简单的实现方法,亲测好用,你也可以根据自己业务来处理数据,设置单元格格式,很简单这里就不详细说明了。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!