Java POI导出EXCEL及样式设计

1、需要的maven依赖.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

2、后台代码及配置

@ApiOperation(value="导出Excel")
	@RequestMapping(value = "/exportFile", method = RequestMethod.GET)
	@ResponseBody
	public void exportFile(@ApiParam Student student, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// 模拟需要导出的数据
		List<Student> students =  new ArrayList<Student>();
		Student stu1 = new Student("001", "张三", "111", 100);
		Student stu2 = new Student("002", "李四", "222", 98);
		Student stu3 = new Student("003", "王五", "333", 99);
		students.add(stu1);
		students.add(stu2);
		students.add(stu3);
		
		// 定义excel标题
		String[] title = { "序号", "学号", "姓名", "身份证号", "成绩" };

		// 定义excel文件名
		String fileName = "五年级一班学生成绩单";

		// 定义sheet名
		String sheetName = "成绩单";
		
		// 封装excel表格内容
		String[][] content = new String[students.size()][title.length];
		for (int i = 0; i < students.size(); i++) {
			Student stu = students.get(i);
			content[i][0] = String.valueOf(i+1);
			content[i][1] = stu.getId();
			content[i][2] = stu.getName();
			content[i][3] = stu.getIdCard();
			content[i][4] = String.valueOf(stu.getScore());
		}

		// 创建HSSFWorkbook,写入sheet名称,标题名称,内容等信息
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook1(fileName, sheetName, title, content, null);
		// 响应到客户端
		try {
			// 获取浏览器的user-agent参数,进行输出文件名称编码格式转换
			String userAgent = request.getHeader("user-agent").toLowerCase();
			if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
				// win10 ie edge 浏览器 和其他系统的ie
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else {
				// 非IE
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			}
			// 设置返回响应为excel类型
			response.reset();
			response.setContentType("application/vnd.ms-excel");
	        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
			// 输出响应
	        OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

ExcelUtil.java

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExcelUtil {
    
    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
	public static HSSFWorkbook getHSSFWorkbook1(String fileName, String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {

		// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
		if (wb == null) {
			wb = new HSSFWorkbook();
		}

		// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet(sheetName);
		
		// 设置当前sheet中默认的列宽为10个字符
		sheet.setDefaultColumnWidth(10);
		// 设置当前sheet中2,3,4列为12,15,20个字符
		sheet.setColumnWidth(2, 12 * 256);
		sheet.setColumnWidth(3, 15 * 256);
		sheet.setColumnWidth(4, 20 * 256);

		// 第三步,在第一行设置标题栏
		// 定义单元格的样式
		HSSFCellStyle cellStyle = wb.createCellStyle();
		// 设置字体样式,13号,加粗
		HSSFFont font1 = wb.createFont();
		font1.setFontHeightInPoints((short) 13);
		font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
		cellStyle.setFont(font1);
		// 设置水平居中
		cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
		// 标题栏所在sheet的行为第一行
		HSSFRow titleRow = sheet.createRow(0);
		// 设置行高
		titleRow.setHeight((short) 500);
		// 设置第一行的第一个单元格
		HSSFCell titleCell = titleRow.createCell(0);
		// 设置标题文本
		titleCell.setCellValue(new HSSFRichTextString(fileName));
		// 设置单元格样式
		titleCell.setCellStyle(cellStyle);
		// 处理单元格合并,四个参数分别是:起始行,终止行,起始行,终止列
		sheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0, (short) (title.length - 1)));
		// 设置合并后的单元格的样式
		titleRow.createCell(title.length - 1).setCellStyle(cellStyle);
		
		// 第四步,在sheet中添加标题行,位于表头第1行,注意老版本poi对Excel的行数列数有限制
		HSSFRow row = sheet.createRow(1);
		// 创建title行cell样式
		HSSFCellStyle style = wb.createCellStyle();
		// 设置title样式剧中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
		// 设置字体
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 13);
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(font);
		// 声明列对象
		HSSFCell cell = null;
		// 创建标题
		for (int i = 0; i < title.length; i++) {
			// 创建cell
			cell = row.createCell(i);
			// 填入内容
			cell.setCellValue(title[i]);
			// 设置cell内容的样式
			cell.setCellStyle(style);
		}

		// 第五步,在sheet中添加内容,位于表头第2行开始
		// 定义内容cell样式
		HSSFCellStyle styleContent = wb.createCellStyle();
		// 设置样式 居中,字体,边框
		styleContent.setAlignment(CellStyle.ALIGN_CENTER);
		font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		styleContent.setFont(font);
		// 设置边框样式
		styleContent.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		styleContent.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		styleContent.setBorderTop(HSSFCellStyle.BORDER_THIN);
		styleContent.setBorderRight(HSSFCellStyle.BORDER_THIN);
		// 创建内容
		for (int i = 0; i < values.length; i++) {
			row = sheet.createRow(i+2);
			for (int j = 0; j < values[i].length; j++) {
				// 将内容按顺序赋给对应的列对象
				HSSFCell createCell = row.createCell(j);
				createCell.setCellValue(values[i][j]);
				createCell.setCellStyle(style);
			}
		}
		return wb;
	}
}

3、前端代码配置

在方法的js中如下即可

let exportUrl = urlConfig.exportCloudLog + '?' + jsonStr;    // 调用接口

exportUrl = encodeURI(exportUrl);   //解码

window.open(exportUrl, '_self');   

4、实例:

特:

1、如果需要字符串内容换行展示。

(1)、设置cellValue值的时候,需要加上\r\n换行符号。可以使用换行字符串对象

HSSFRichTextString

(2)、cell设置样式如下

效果

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值