java导出excel 【POI 3.17】POI 版本不匹配解决方法

目录 

1.Maven依赖

2.ExcelUtil工具类代码

3.Test测试

4.遇到的问题


公司要写导出Excel的功能,就写了一下,顺便记录记录,代码从这里copy来的,自己改了一下。源码应该是3.9的poi版本,里面挺多类已经不推荐使用了,我用的poi是3.17。

1.Maven依赖

		<!-- 数据导出到xlsx -->
		<dependency>
			<groupId>org.apache.xmlbeans</groupId>
			<artifactId>xmlbeans</artifactId>
			<version>2.6.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>

 2.ExcelUtil工具类代码

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import static org.apache.poi.ss.usermodel.CellType.NUMERIC;

public class ExcelUtil {

	/**
	 * 导出excel
	 *
	 * @param title    导出表的标题
	 * @param rowsName 导出表的列名
	 * @param dataList 需要导出的数据
	 * @param fileName 生成excel文件的文件名
	 * @param response
	 */
	public void exportExcel(String title, String[] rowsName, List<String[]> dataList, String fileName, HttpServletResponse response) throws Exception {
		OutputStream output = response.getOutputStream();
		response.reset();
		response.setHeader("Content-disposition",
				"attachment; filename=" + fileName);
		response.setContentType("application/msexcel");
		this.export(title, rowsName, dataList, fileName, output);
		this.close(output);
	}

	/**
	 * 数据导出
	 * @param title
	 * @param rowName
	 * @param dataList
	 * @param fileName
	 * @param out
	 * @throws Exception
	 */
	private void export(String title, String[] rowName, List<String[]> dataList, String fileName, OutputStream out) throws Exception {
		//查看poi使用的是什么版本的jar包
		//System.out.println("!!!!!!!!!"+ XSSFCellStyle.class.getProtectionDomain().getCodeSource().getLocation());
		try {
			// 创建工作簿对象
			XSSFWorkbook workbook = new XSSFWorkbook();
			// 创建工作表
			XSSFSheet sheet = workbook.createSheet(title);
			// 产生表格标题行
			XSSFRow rowm = sheet.createRow(0);
			//创建表格标题列
			XSSFCell cellTiltle = rowm.createCell(0);
			// sheet样式定义;    getColumnTopStyle();    getStyle()均为自定义方法 --在下面,可扩展
			// 获取列头样式对象
			XSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
			// 获取单元格样式对象
			XSSFCellStyle style = this.getStyle(workbook);
			//合并表格标题行,合并列数为列名的长度,第一个0为起始行号,第二个1为终止行号,第三个0为起始列好,第四个参数为终止列号
			sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
			//设置标题行样式
			cellTiltle.setCellStyle(columnTopStyle);
			//设置标题行值
			cellTiltle.setCellValue(title);
			// 定义所需列数
			int columnNum = rowName.length;
			// 在索引2的位置创建行(最顶端的行开始的第二行)
			XSSFRow rowRowName = sheet.createRow(2);
			// 将列头设置到sheet的单元格中
			for (int n = 0; n < columnNum; n++) {
				// 创建列头对应个数的单元格
				XSSFCell cellRowName = rowRowName.createCell(n);
				// 设置列头单元格的数据类型
				cellRowName.setCellType(CellType.STRING);
				XSSFRichTextString text = new XSSFRichTextString(rowName[n]);
				// 设置列头单元格的值
				cellRowName.setCellValue(text);
				// 设置列头单元格样式
				cellRowName.setCellStyle(columnTopStyle);
			}

			// 将查询出的数据设置到sheet对应的单元格中
			for (int i = 0; i < dataList.size(); i++) {
				// 遍历每个对象
				Object[] obj = dataList.get(i);
				// 创建所需的行数
				XSSFRow row = sheet.createRow(i + 3);
				for (int j = 0; j < obj.length; j++) {
					// 设置单元格的数据类型
					XSSFCell cell = null;
					if (j == 0) {
						cell = row.createCell(j, NUMERIC);
						cell.setCellValue(i + 1);
					} else {
						cell = row.createCell(j, CellType.STRING);
						if (!"".equals(obj[j]) && obj[j] != null) {
							// 设置单元格的值
							cell.setCellValue(obj[j].toString());
						}
					}
					cell.setCellStyle(style); // 设置单元格样式
				}
			}

			// 让列宽随着导出的列长自动适应
			for (int colNum = 0; colNum < columnNum; colNum++) {
				int columnWidth = sheet.getColumnWidth(colNum) / 256;
				for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
					XSSFRow currentRow;
					// 当前行未被使用过
					if (sheet.getRow(rowNum) == null) {
						currentRow = sheet.createRow(rowNum);
					} else {
						currentRow = sheet.getRow(rowNum);
					}
					if (currentRow.getCell(colNum) != null) {
						XSSFCell currentCell = currentRow.getCell(colNum);
						if (currentCell.getCellType() == 1) {
							int length = currentCell.getStringCellValue()
									.getBytes().length;
							if (columnWidth < length) {
								columnWidth = length;
							}
						}
					}
				}
				if (colNum == 0) {
					sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
				} else {
					sheet.setColumnWidth(colNum, (columnWidth + 8) * 256);
				}
			}
			workbook.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 列头单元格样式
	 */
	private XSSFCellStyle getColumnTopStyle(XSSFWorkbook workbook) {

		// 设置字体
		XSSFFont font = workbook.createFont();
		// 设置字体大小
		font.setFontHeightInPoints((short) 16);
		// 字体加粗
		font.setBold(true);
		// 设置字体名字
		font.setFontName("Courier New");
		// 设置样式;
		XSSFCellStyle style = workbook.createCellStyle();
		// 设置底边框;
		style.setBorderBottom(BorderStyle.THIN);
		// 设置底边框颜色;
		style.setBottomBorderColor(new XSSFColor(Color.BLACK));
		// 设置左边框;
		style.setBorderLeft(BorderStyle.THIN);
		// 设置左边框颜色;
		style.setLeftBorderColor(new XSSFColor(Color.BLACK));
		// 设置右边框;
		style.setBorderRight(BorderStyle.THIN);
		// 设置右边框颜色;
		style.setRightBorderColor(new XSSFColor(Color.BLACK));
		// 设置顶边框;
		style.setBorderTop(BorderStyle.THIN);
		// 设置顶边框颜色;
		style.setTopBorderColor(new XSSFColor(Color.BLACK));
		// 在样式用应用设置的字体;
		style.setFont(font);
		// 设置自动换行;
		style.setWrapText(false);
		// 设置水平对齐的样式为居中对齐;
		style.setAlignment(HorizontalAlignment.CENTER);
		// 设置垂直对齐的样式为居中对齐;
		style.setVerticalAlignment(VerticalAlignment.CENTER);

		return style;

	}

	/*
	 * 列数据信息单元格样式
	 */
	private XSSFCellStyle getStyle(XSSFWorkbook workbook) {
		// 设置字体
		XSSFFont font = workbook.createFont();
		// 设置字体大小
		// font.setFontHeightInPoints((short)10);
		// 字体加粗
		// font.setBold(true);
		// 设置字体名字
		font.setFontName("Courier New");
		// 设置样式;
		XSSFCellStyle style = workbook.createCellStyle();
		// 设置底边框;
		style.setBorderBottom(BorderStyle.THIN);
		// 设置底边框颜色;
		//style.setBottomBorderColor(new XSSFColor(Color.RED));
		// 设置左边框;
		style.setBorderLeft(BorderStyle.THIN);
		// 设置左边框颜色;
		style.setLeftBorderColor(new XSSFColor(Color.BLACK));
		// 设置右边框;
		style.setBorderRight(BorderStyle.THIN);
		// 设置右边框颜色;
		style.setRightBorderColor(new XSSFColor(Color.BLACK));
		// 设置顶边框;
		style.setBorderTop(BorderStyle.THIN);
		// 设置顶边框颜色;
		style.setTopBorderColor(new XSSFColor(Color.BLACK));
		// 在样式用应用设置的字体;
		style.setFont(font);
		// 设置自动换行;
		style.setWrapText(false);
		// 设置水平对齐的样式为居中对齐;
		style.setAlignment(HorizontalAlignment.CENTER);
		// 设置垂直对齐的样式为居中对齐;
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		return style;
	}

	/**
	 * 关闭输出流
	 *
	 * @param os
	 */
	private void close(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

 3.Test测试

@GetMapping("/test")
public R test(HttpServletResponse response) {
	ExcelUtil excelUtil = new ExcelUtil();
	List<String[]> el = new ArrayList<>();

	//需要导出的数据
	List<ReportLogDataDto> reportList = reportService.getReportList();

	if (reportList.isEmpty()) {
		return R.failed("查询到的报表条数为0");
	}

	//遍历取出数据,封装成List<String[]>的形式
	reportList.forEach(item -> {
		int count = 0;
		String[] col = new String[8];
                //这行是给编号留出一个空位
		col[count++] = "";
		col[count++] = item.getCode();
		col[count++] = item.getRoomName();
		col[count++] = item.getStartTime();
		col[count++] = item.getEndTime();
		col[count++] = item.getIsFinished();
		col[count++] = item.getFailureReason();
		col[count++] = item.getTime();
		el.add(col);
	});

	//这里是列名
	String[] name = {"编号", "设备编号", "房间名", "开始时间", "结束时间", "是否完成消毒", "失败原因", "时间段"};
	try {
		excelUtil.exportExcel("消毒报表", name, el, "DisinfectionReport.xlsx", response);
		System.out.println("excel finished");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return R.ok();
}

我是用SwaggerUI看的,结果如下: 

 4.遇到的问题

1)jar包的升级导致CELL_TYPE_STRING、XSSFCell.CELL_TYPE_NUMERIC等无法使用

    可以使用CellType.STRING、CellType.NUMERIC等等代替。图片是CellType中的内容,可以看出,从3.15就可以使用新的参数了。新的版本都会有旧版本的替代方法,改改就好了。

 

    同时,以下也可以进行替换

POI旧版本POI新版本
HSSFCellStyle.BORDER_THINBorderStyle.THIN
HSSFColor.BLACK.indexnew XSSFColor(Color.BLACK)
HSSFCellStyle.ALIGN_CENTERHorizontalAlignment.CENTER
HSSFCellStyle.VERTICAL_CENTERVerticalAlignment.CENTER

2)Caused by: java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.XSSFCell.setEncoding(S)V 

    这可能是由于poi版本覆盖,或者没有正确的引用poi的jar包导致的,我最开始用的jar包,应该是poi3.9,但是下载依赖的时候,会自动把3.17的版本也下载下来,自动覆盖了3.9的版本,导致虽然没有报错,但是 HSSFCellStyle 和部分class一直提示NoSuchMethodError。

    ExcelUtil代码中有一行sysout语句如下,这行会把使用的class所在的路径打印出来,通过打印出的信息,可以看看自己用的jar包到底是哪里的,版本号是多少,这个其实也算是版本升级导致的问题了。建议使用新版本的poi,别用老的了。

 

System.out.println("!!!!!!!!!"+ XSSFCellStyle.class.getProtectionDomain().getCodeSource().getLocation());

 

引用:

https://www.cnblogs.com/duanrantao/p/8683022.html

https://www.cnblogs.com/qxqbk/p/7655307.html

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用POI库可以实现Excel文件的操作,包括读取、写入、修改等。下面是使用POI库实现带图片的模板导出Excel的示例代码: 1. 导入依赖库 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.17</version> </dependency> ``` 2. 创建Excel模板 创建一个Excel模板,包含需要导出的数据和图片。示例模板如下: ![excel_template.png](https://cdn.jsdelivr.net/gh/occlive/ImageHost01/excel_template.png) 3. 编写Java代码 Excel模板创建完成后,就可以使用POI库来读取模板、填充数据和图片、导出Excel文件了。以下是示例代码: ```java import java.io.*; import java.util.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; public class ExcelExportUtil { public static void export(List<Map<String, Object>> dataList, String templatePath, String exportPath) throws Exception { InputStream is = new FileInputStream(templatePath); XSSFWorkbook workbook = new XSSFWorkbook(is); XSSFSheet sheet = workbook.getSheetAt(0); int rowIndex = 1; for (Map<String, Object> data : dataList) { XSSFRow row = sheet.createRow(rowIndex++); int cellIndex = 0; for (String key : data.keySet()) { Object value = data.get(key); XSSFCell cell = row.createCell(cellIndex++); if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Double) { cell.setCellValue((Double) value); } else if (value instanceof Date) { cell.setCellValue((Date) value); } else if (value instanceof Calendar) { cell.setCellValue((Calendar) value); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } else if (value instanceof byte[]) { // 插入图片 int pictureIdx = workbook.addPicture((byte[]) value, Workbook.PICTURE_TYPE_JPEG); CreationHelper helper = workbook.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(cellIndex - 1); anchor.setRow1(rowIndex - 1); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(); } else { cell.setCellValue(value.toString()); } } } OutputStream os = new FileOutputStream(exportPath); workbook.write(os); os.close(); } } ``` 代码解释: - `export`方法接受一个数据列表、一个Excel模板文件路径和一个导出Excel文件路径作为参数,将数据填充到模板中并导出Excel文件 - 首先使用`FileInputStream`读取Excel模板文件,然后创建`XSSFWorkbook`和`XSSFSheet`对象 - 遍历数据列表,对于每个数据项,创建一个新的行,并为每个属性创建一个单元格,使用单元格的`setCellValue`方法填充数据 - 如果属性的值是一个图片,则调用`Workbook.addPicture`方法将图片添加到工作簿中,并使用`Sheet.createDrawingPatriarch`方法创建绘图对象,在单元格上创建图片,最后调用`Picture.resize`方法调整图片大小 - 最后使用`FileOutputStream`将工作簿写入Excel文件中 4. 调用导出方法 在main方法中调用export方法进行导出: ```java import java.util.*; public class Main { public static void main(String[] args) throws Exception { List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> data1 = new HashMap<>(); data1.put("name", "张三"); data1.put("age", 20); data1.put("avatar", FileUtils.readFileToByteArray(new File("avatar.jpg"))); dataList.add(data1); Map<String, Object> data2 = new HashMap<>(); data2.put("name", "李四"); data2.put("age", 25); data2.put("avatar", FileUtils.readFileToByteArray(new File("avatar.jpg"))); dataList.add(data2); ExcelExportUtil.export(dataList, "template.xlsx", "export.xlsx"); } } ``` 以上代码会生成一个包含两条记录和图片的Excel文件,效果如下: ![excel_export.png](https://cdn.jsdelivr.net/gh/occlive/ImageHost01/excel_export.png) 希望对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值