Spring-shiro-Boot-15 Apache POI的实现与ExcelUtil

本文介绍了如何在Spring Boot项目中利用Apache POI库进行Excel文件的处理,包括导入所需包,POI对Microsoft文档的兼容性,以及通过ExcelUtil导出Excel的三个关键步骤:创建Excel模板,指定位置导出,以及直接导出到浏览器。

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

ApachePOI是用Java编写的免费开源的跨平台的JavaAPI,在程序中的使用一般是用来简单处理Excel文件。

1、引入包

        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>${poi.version}</version>
		</dependency>

2、POI可以操作各种类型的Microsoft文档

HSSF-提供读写ExcelXLS
XSSF-提供读写ExcelOOXMLXLSX
HWPF-提供读写WordDOC
HSLF-提供读写PowerPoint
HDGF-提供读Visio
HPBF-提供读Publisher
HSMF-提供读Outlook

3、execl导出,ExcelUtil的三个方法。

(1)准备execl

1、准备创建相关数据
2、设置列头相关内容
3、渲染数据
4、列宽自适应
public static Workbook getWorkbook(String[] headers, List<Object[]> datas) {
		//1、准备创建相关数据
		//加载指定文件,创建一个Excel对象(工作簿)
		Workbook workbook = new HSSFWorkbook();
		//读取Excel文件中第一个Sheet标签页
		Sheet sheet = workbook.createSheet();
		//行
		Row row = null;
		//单元格
		Cell cell = null;
        //创建单元格样式
		CellStyle style = workbook.createCellStyle();
		//设置单元格水平居中
		style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
		//设置字体格式
		Font font = workbook.createFont();

		int line = 0, maxColumn = 0;
		// 2、设置列头相关内容
		if (headers != null && headers.length > 0) {
			//创建一行
			row = sheet.createRow(line++);
			//设置行高
			row.setHeightInPoints(23);
			//设置文字为粗体
			font.setBold(true);
			//设置高度
			font.setFontHeightInPoints((short) 13);
			//采用字体
			style.setFont(font);
			//设置首行单元格数目
			maxColumn = headers.length;
			//为每一单元格设置值和格式
			for (int i = 0; i < maxColumn; i++) {
				//创建单元格
				cell = row.createCell(i);
				//设置单元格列名
				cell.setCellValue(headers[i]);
				//设置单元格格式
				cell.setCellStyle(style);
			}
		}
		// 3、渲染数据
		if (datas != null && datas.size() > 0) {
			//遍历每一行数据
			for (int index = 0, size = datas.size(); index < size; index++) {
				Object[] data = datas.get(index);
				if (data != null && data.length > 0) {
					row = sheet.createRow(line++);
					//设置行高
					row.setHeightInPoints(20);

					int length = data.length;
					if (length > maxColumn) {
						maxColumn = length;
					}
                    //设置行内单元格
					for (int i = 0; i < length; i++) {
						cell = row.createCell(i);
						//设置单元格内容
						cell.setCellValue(data[i] == null ? null : data[i].toString());
					}
				}
			}
		}
        //4、列宽自适应
		for (int i = 0; i < maxColumn; i++) {
			sheet.autoSizeColumn(i);
			//如果该列为中文,会出现列宽不足现象。
			// 解决自动设置列宽中文失效的问题
			//sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
		}

		return workbook;
	}

(2)导出到指定位置

1、获取execl
2、写出到字节流中
3、字节流转文件流写出到指定位置
4、关闭相关资源
public static void excelLocal(String path, String fileName, String[] headers, List<Object[]> datas) {
		//1、获取execl
		Workbook workbook = getWorkbook(headers, datas);
		if (workbook != null) {
			ByteArrayOutputStream byteArrayOutputStream = null;
			FileOutputStream fileOutputStream = null;
			try {
				byteArrayOutputStream = new ByteArrayOutputStream();
				//2、写出到字节流中
				workbook.write(byteArrayOutputStream);

				String suffix = ".xls";
				File file = new File(path + File.separator + fileName + suffix);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				fileOutputStream = new FileOutputStream(file);
				//3、字节流转文件流写出到指定位置
				fileOutputStream.write(byteArrayOutputStream.toByteArray());
			} catch (Exception e) {
				e.printStackTrace();
				//4、关闭相关资源
			} finally {
				try {
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if (byteArrayOutputStream != null) {
						byteArrayOutputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					workbook.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

(3)导出excel到浏览器

1、获取execl
2、写出到字节流中
3、设置相关响应参数
4、字节流转文件流写出到response
5、关闭相关资源
public static void excelExport(String fileName, String[] headers, List<Object[]> datas,
			HttpServletResponse response) {
		//1、获取execl
		Workbook workbook = getWorkbook(headers, datas);
		if (workbook != null) {
			ByteArrayOutputStream byteArrayOutputStream = null;
			try {
				byteArrayOutputStream = new ByteArrayOutputStream();
				//2、写出到字节流中
				workbook.write(byteArrayOutputStream);

				//3、设置相关响应参数
				String suffix = ".xls";
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((fileName + suffix).getBytes(), "iso-8859-1"));

				OutputStream outputStream = response.getOutputStream();
				//4、字节流转文件流写出到response
				outputStream.write(byteArrayOutputStream.toByteArray());
				outputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
				//5、关闭相关资源
			} finally {
				try {
					if (byteArrayOutputStream != null) {
						byteArrayOutputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					workbook.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良之才-小良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值