使用POI导出数据到Excel

使用POI导出数据到Excel

一、概述

  1. Apache POI - 用于Microsoft文档的Java API
  2. 下载:http://poi.apache.org/index.html
    指南:https://poi.apache.org/spreadsheet/quick-guide.html
  3. maven下载:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16-beta2</version>
</dependency>
  1. 依赖文件:
    poi-3.16-beta2.jar
    commons-codec-1.10.jar
    commons-collections4-4.1.jar
  2. 基础案例:
//创建一个项目根目录下的文件test.xls
FileOutputStream fos = new FileOutputStream("test.xls");
//创建工作簿
Workbook wb = new HSSFWorkbook();
//在工作簿中创建工作表,工作表默认名为sheet0,参数为工作表名称
Sheet sheet = wb.createSheet("新工作表");
int rownum = 1;
//创建一个行
Row row = sheet.createRow(rownum);
int colnum = 1;
//创建一个单元格
Cell cell = row.createCell(colnum);
//设置单元格的值
cell.setCellValue("一个单元格");
//将工作簿数据写入到输出流中
wb.write(fos);
//关闭输出流
fos.close();
  1. 创建一个日期格式的单元格
//创建一个单元格
Cell cell = row.createCell(colnum);
//设置单元格的值
cell.setCellValue(new Date());

CreationHelper createHelper = wb.getCreationHelper();
//单元格样式
CellStyle style = wb.createCellStyle();
//设置单元格样式内容
style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
//设置数字格式
//style.setDataFormat(createHelper.createDataFormat().getFormat("###,###.00"));
//设置单元格关联的样式
cell.setCellStyle(style);

//也可以使用Calendar
cell.setCellValue(Calendar.getInstance());
  1. 设置边框
CellStyle style = wb.createCellStyle();
	
//设置单元格关联的样式
cell.setCellStyle(style);
//设置单元格底边
style.setBorderBottom(BorderStyle.THIN);
//设置单元格底边颜色
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());

style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());

style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());

style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
  1. 自动调整列宽度
sheet.autoSizeColumn(1);//sheet为工作表,参数为列号
  1. 创建字体(包括设置字体颜色)
//创建字体
Font font = wb.createFont();
//设置字体高位24像素
font.setFontHeightInPoints((short)24);
//设置字体名字
font.setFontName("宋体");
//设置是否为斜体
font.setItalic(true);
//设置是否有删除线
font.setStrikeout(true);
//设置字体颜色
font.setColor(IndexedColors.BLUE.index);
//将字体与样式关联
style.setFont(font);

//设置字体后,自动调整列宽
sheet.autoSizeColumn(1);
  1. 合并单元格
sheet.addMergedRegion(new CellRangeAddress(
		1, //开始第一行行号,从0开始
		1, //结束行行号,从0开始
		1, //开始第一列列号,从0开始
		10 //结束列列号,从0开始
	));
  1. 对齐
CellStyle style = wb.createCellStyle();
//设置水平居中
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直居中
style.setVerticalAlignment(VerticalAlignment.CENTER);

cell.setCellStyle(style);
  1. 设置填充前景色
//填充前景,而不是字体颜色
style.setFillForegroundColor(IndexedColors.BLUE.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  1. 设置列宽度
//参数1为列号(从0开始),参数2为列宽,单位为一个字符的1/256的宽度
sheet.setColumnWidth(0, 8000);

二、javaweb项目中集成poi

  1. Servlet中
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//创建工作簿
	Workbook wb = new HSSFWorkbook();
	//在工作簿中创建工作表
	Sheet sheet = wb.createSheet();
	int rownum = 1;
	//创建一个行
	Row row = sheet.createRow(rownum);
	int colnum = 1;
	//创建一个单元格
	Cell cell = row.createCell(colnum);
	//设置单元格的值
	cell.setCellValue("123456");	
	
	//设置响应内容类型
       response.setContentType("application/vnd.ms-excel");   
       //设置响应头
       response.setHeader("Content-disposition", "attachment;filename=student.xls");    
       
	OutputStream ouputStream = response.getOutputStream();   
       //将工作簿写入到响应流中
       wb.write(ouputStream);  
       ouputStream.close();    
}
  1. 文件名为中文的解决:
response.setHeader("Content-disposition", "attachment;filename="+new String("学生".getBytes("utf-8"),"iso-8859-1")+".xls"); 

三、SSM框架中使用(同java web相同)

实用案例:

@RequestMapping("/export2")
public void export2(HttpServletResponse response) throws IOException{
	List<Dept> list = deptService.pagedData(0, 0);
	//创建工作簿
	Workbook wb = new HSSFWorkbook();
	//在工作簿中创建工作表
	Sheet sheet = wb.createSheet();		
	
	//创建字体
	Font titleFont = wb.createFont();
	//设置字体高位24像素
	titleFont.setFontHeightInPoints((short)24);
	//设置字体名字
	titleFont.setFontName("宋体");	
	titleFont.setColor(IndexedColors.BLUE.index);
	
	CellStyle titleStyle = wb.createCellStyle();
	//将字体与样式关联
	titleStyle.setFont(titleFont);
	//水平居中
	titleStyle.setAlignment(HorizontalAlignment.CENTER);
	
	Row titleRow = sheet.createRow(0);
	createCell(titleRow, 1,titleStyle).setCellValue("部门信息");
	//合并单元格
	sheet.addMergedRegion(new CellRangeAddress(
			0, //开始第一行行号,从0开始
			0, //结束行行号,从0开始
			1, //开始第一列列号,从0开始
			3 //结束列列号,从0开始
		));
	
	//创建字体
	Font font = wb.createFont();
	//设置字体高位24像素
	font.setFontHeightInPoints((short)20);
	//设置字体名字
	font.setFontName("宋体");	
	
	CellStyle style = wb.createCellStyle();
	//将字体与样式关联
	style.setFont(font);
	style.setAlignment(HorizontalAlignment.CENTER);
	
	Font fontContent = wb.createFont();
	//设置字体高位24像素
	fontContent.setFontHeightInPoints((short)16);
	//设置字体名字
	fontContent.setFontName("宋体");	
	
	CellStyle styleContent = wb.createCellStyle();
	//将字体与样式关联
	styleContent.setFont(font);
	
	int rownum = 1;		
	int colDefaultNum = 1;
	int colnum = colDefaultNum;
	Row row;
	Cell cell;
	//插入列头
	row = sheet.createRow(rownum++);		
	
	setBorder(style);
	createCell(row,colnum++,style).setCellValue("部门编号");
	createCell(row,colnum++,style).setCellValue("部门名称");
	createCell(row,colnum++,style).setCellValue("部门地址");
	
	setBorder(styleContent);
	for(Dept dept : list){
		colnum = colDefaultNum;
		//创建一个行
		row = sheet.createRow(rownum++);	
		
		createCell(row,colnum++,styleContent).setCellValue(dept.getDeptno());
		createCell(row,colnum++,styleContent).setCellValue(dept.getDname());
		createCell(row,colnum++,styleContent).setCellValue(dept.getLoc());				
	}
	
	colnum = colDefaultNum;
	sheet.autoSizeColumn(colnum++);
	sheet.autoSizeColumn(colnum++);
	sheet.autoSizeColumn(colnum++);
	
	//设置响应内容类型
       response.setContentType("application/vnd.ms-excel");   
       //设置响应头
       response.setHeader("Content-disposition", "attachment;filename="+new String("学生".getBytes("utf-8"),"iso-8859-1")+".xls");    
       OutputStream ouputStream = response.getOutputStream();   
       //将工作簿写入到响应流中
       wb.write(ouputStream);  
       ouputStream.close();    		
}

private Cell createCell(Row row,int colNum,CellStyle style){
	Cell cell = row.createCell(colNum);
	if(style != null){
		cell.setCellStyle(style);
	}	
	
	return cell;
}

private Cell createCell(Row row,int colNum){
	Cell cell = createCell(row,colNum,null);
	
	return cell;
}

private void setBorder(CellStyle style){
	style.setBorderBottom(BorderStyle.THIN);
	//设置单元格底边颜色
	style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	
	style.setBorderLeft(BorderStyle.THIN);
	style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	
	style.setBorderTop(BorderStyle.THIN);
	style.setTopBorderColor(IndexedColors.BLACK.getIndex());
	
	style.setBorderRight(BorderStyle.THIN);
	style.setRightBorderColor(IndexedColors.BLACK.getIndex());
}

视频讲解、笔记和源码下载

https://download.csdn.net/download/pcbhyy/10764351

下载资料目录结构

  1. poi-bin-3.16-20170419.zip:poi二进制分发包(包括文档)
  2. poi_demo:java演示项目
  3. javaweb_poi_demo:javaweb演示项目
  4. ssm_poi_page_demo:ssm演示项目(实现了完整dept表数据导出功能)
  5. 学生.xls:ssm项目导出excel文件

猜你喜欢

转载自blog.csdn.net/pcbhyy/article/details/83721722