java中使用poi导出Excel表格通用方法

最近做的项目中导出功能做的比较多,所以根据经验自己写了一个导出的公用类,供大家参考:

1、加入maven依赖

<!-- 导出excel文件-->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.9</version>
</dependency>

2、创建导出类,属性值不用提供getter和setter方法

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 导出Excel表格工具类
 */
public class ExportExcel {

	private String[] rowName;//列名名称

	private List<Object[]> objList = new ArrayList<Object[]>(); //要到处的数据信息

	private String name;//表头名称
	
	// 构造方法,传入要导出的数据
	public ExportExcel(List<Object[]> objList, String[] rowName, String name) {
		this.objList = objList;
		this.rowName = rowName;
		this.name = name;
	}
.
.
.
}

3、创建单元表格头的样式

    /**
	 * 列头单元格样式
	 */
	public CellStyle getColumnTopStyle(XSSFWorkbook workbook,int fontSize) {
		// 设置字体
		XSSFFont font = workbook.createFont();
		// 设置字体大小
		font.setFontHeightInPoints((short) fontSize);
		// 字体加粗
		font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
		// 设置字体名字
		font.setFontName("宋体");
		// 设置列头字体的颜色
		font.setColor(HSSFColor.VIOLET.index);
		// 设置样式
		CellStyle style = workbook.createCellStyle();
		// 在样式用应用设置的字体
		style.setFont(font);
		// 设置自动换行
		style.setWrapText(false);
		// 设置水平对齐的样式为居中对齐
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		// 设置垂直对齐的样式为居中对齐
		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		// 设置单元格填充颜色
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);

		// 设置边框及颜色
		style.setBorderBottom(XSSFCellStyle.BORDER_THIN);//
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderRight(XSSFCellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderTop(XSSFCellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());

		style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		return style;
	}

4、创建单元表格体的样式

    /**
	 * 列数据信息单元格样式
	 */
	public CellStyle getStyle(XSSFWorkbook workbook) {
		// 设置字体
		XSSFFont font = workbook.createFont();
		// 设置字体大小
		font.setFontHeightInPoints((short) 10);
		// 字体加粗
		font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
		// 设置字体名字
		font.setFontName("宋体");
		// 设置样式
		CellStyle style = workbook.createCellStyle();
		// 在样式用应用设置的字体
		style.setFont(font);
		// 设置自动换行
		style.setWrapText(true);
		// 设置水平对齐的样式为居中对齐
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		// 设置垂直对齐的样式为居中对齐
		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		// 设置边框及颜色
		style.setBorderBottom(XSSFCellStyle.BORDER_THIN);//
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderRight(XSSFCellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());

		style.setBorderTop(XSSFCellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		return style;
	}

5、导出操作,对response的header设置可以防止在ie浏览器中的中文乱码问题

    public void export(HttpServletResponse response) throws Exception {
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作薄对象
			XSSFSheet sheet = workbook.createSheet(name); // 创建工作表
			// sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法-在下面-可扩展】
			CellStyle style = this.getStyle(workbook);// 单元格样式对象
			style.setWrapText(false);
			int columnlot = rowName.length;
			// 将j缴费信息列头设置到sheet的单元格中
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnlot - 1));
			// 设置表头
			XSSFRow titleRow = sheet.createRow(0);
			// 添加边框
			CellStyle topStyle = this.getColumnTopStyle(workbook,16);// 获取列头样式对象
			titleRow.setHeightInPoints((short)30);//设置表头的行高
			for (int i = 0; i < columnlot; i++) {
				XSSFCell titleCell = titleRow.createCell(i);
				titleCell.setCellStyle(topStyle);
				titleCell.setCellValue(name);
			}

			XSSFRow lotrowRowName = sheet.createRow(1);// 在索引2的位置创建行(最顶端的行开始的第二行)
			CellStyle columnTopStyle = this.getColumnTopStyle(workbook,12);// 获取列头样式对象
			for (int n = 0; n < columnlot; n++) {
				XSSFCell cellRowName = lotrowRowName.createCell(n);// 创建列头对应个数的单元格
				// cellRowName.setCellType(XSSFCell.CELL_TYPE_STRING);//设置列头单元格的数据类型

				// XSSFRichTextString text = new XSSFRichTextString(rowName[n]);
				cellRowName.setCellValue(rowName[n]);// 设置列头单元格的值

				cellRowName.setCellStyle(columnTopStyle);// 设置列头单元格样式
			}
			// 将查询出的价格批次信息数据设置到sheet对应的单元格中
			for (int i = 0; i < objList.size(); i++) {
				Object[] obj = objList.get(i); // 遍历每个对象
				XSSFRow row = sheet.createRow(2 + i); // 创建所需的行数
				row.setHeightInPoints(16);
				for (int j = 0; j < obj.length; j++) {
					XSSFCell cell = null; // 设置单元格的数据类型
					cell = row.createCell(j, XSSFCell.CELL_TYPE_STRING);
					if (!"".equals(obj[j]) && obj[j] != null) {
						cell.setCellValue(obj[j].toString()); // 设置单元格的值
					}
					cell.setCellStyle(style); // 设置单元格样式
				}
			}
			// 让列宽随着导出的列长自动适应
			for (int i = 0; i < columnlot; i++) {
				sheet.autoSizeColumn(i);
			}

			for (int colNum = 0; colNum < columnlot; 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() == XSSFCell.CELL_TYPE_STRING) {
							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 * 256);
				}
			}

			// 设置第二行行高
			XSSFRow row = sheet.getRow(1);
			row.setHeightInPoints(20);
			
			if (workbook != null) {
				try {
					ByteArrayOutputStream os = new ByteArrayOutputStream();
					workbook.write(os);
					byte[] content = os.toByteArray();
					InputStream is = new ByteArrayInputStream(content);
					// 设置response参数,可以打开下载页面
					String fileName = name + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//文件名称设置为 表头名称 + 14位当前时间戳
					response.reset();
					response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//					response.setHeader("Content-Disposition","attachment;filename=" + new String((filename).getBytes(), "iso-8859-1"));
					response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8")+".xlsx");//为了解决在IE浏览器中汉字乱码的问题
					response.setHeader("Last-Modified", ReportToolUtil.systemDateFormat());
					response.setContentLength(content.length);
					ServletOutputStream outputStream = response.getOutputStream();
					BufferedInputStream bis = new BufferedInputStream(is);
					BufferedOutputStream bos = new BufferedOutputStream(outputStream);
					byte[] buff = new byte[8192];
					int bytesRead;
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						bos.write(buff, 0, bytesRead);
					}
					bis.close();
					bos.close();
					outputStream.flush();
					outputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

6.调用举例

public void exportExcelTest(HttpServletRequest request,HttpServletResponse response,@RequestHeader HttpHeaders headers) {
		try {
			List<String[]> ObjectList = new ArrayList<String[]>();//表格的值
			String[] objs = null;
			for(int i = 0; i < 5; i++) {
				objs = new String[9];
				objs[0] = String.valueOf(i+1);
				objs[1] = "孙悟空"+i+"号";
				objs[2] = String.valueOf(501+i);
				objs[3] = "102";
				objs[4] = "中国";
				objs[5] = String.valueOf(165+i);
				objs[6] = String.valueOf(70+i);
				objs[7] = "男";
				objs[8] = "测试";
				ObjectList.add(objs);
			}
			//表头
			String[] rowName = {"序号","姓名","年龄","尺寸","国家","身高","体重","性别","备注"};
			ExportExcel exportExcel = new ExportExcel(ObjectList, rowName, "测试导出表格");
			exportExcel.export(response);
		}catch(Exception ex) {
			logger.error("异常:",ex);
		}
		
	}

7.可以模拟由页面发起一个http请求,查询导出效果。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值