pom文件添加:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Excel实体类,把要导出的数据存放到实体类中
public class Excel {
//数据库字段名,导出时无用
private String key;
//数据内容
private Object value;
//数据类型
private String type;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Excel(String key, Object value, String type) {
this.key = key;
this.value = value;
this.type = type;
}
public Excel() {
}
}
ExcelFormatUtil 样式工具类,Excel表格样式
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
/**
* excle样式工具类
*/
public class ExcelFormatUtil {
/**
* 设置报表头样式
* @param workbook
* @return
*/
public static CellStyle headSytle(HSSFWorkbook workbook){
// 设置style1的样式,此样式运用在第二行
CellStyle style1 = workbook.createCellStyle();// cell样式
// 设置单元格背景色,设置单元格背景色以下两句必须同时设置
style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置填充色
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
Font font1 = workbook.createFont();// 创建一个字体对象
font1.setBoldweight((short) 10);// 设置字体的宽度
font1.setFontHeightInPoints((short) 10);// 设置字体的高度
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
style1.setFont(font1);// 设置style1的字体
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
* 设置报表体样式
* @param wb
* @return
*/
public static CellStyle contentStyle(HSSFWorkbook wb){
// 设置style1的样式,此样式运用在第二行
CellStyle style1 = wb.createCellStyle();// cell样式
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
* 设置报表标题样式
* @param workbook
* @return
*/
public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){
// 设置style1的样式,此样式运用在第二行
HSSFCellStyle style1 = workbook.createCellStyle();// cell样式
// 设置单元格背景色,设置单元格背景色以下两句必须同时设置
//style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
//short fcolor = color;
if(color != HSSFColor.WHITE.index){
style1.setFillForegroundColor(color);// 设置填充色
}
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
HSSFFont font1 = workbook.createFont();// 创建一个字体对象
font1.setBoldweight(fontSize);// 设置字体的宽度
font1.setFontHeightInPoints(fontSize);// 设置字体的高度
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
style1.setFont(font1);// 设置style1的字体
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
*设置表头
* @param sheet
*/
public static void initTitleEX(HSSFSheet sheet, CellStyle header, String title[], int titleLength) {
HSSFRow row0 = sheet.createRow(0);
row0.setHeight((short) 800);
for(int j = 0;j<title.length; j++) {
HSSFCell cell = row0.createCell(j);
//设置每一列的字段名
cell.setCellValue(title[j]);
cell.setCellStyle(header);
sheet.setColumnWidth(j, titleLength);
}
}
}
导出工具类
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.util.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Validated
public class ExportTools{
/**
*
* strs 表头
* */
public static InputStream export(List<Map> list , String[] strs , String[] zds) {
ByteArrayOutputStream output = null;
InputStream inputStream1 = null;
HSSFWorkbook wb = new HSSFWorkbook();// 保留1000条数据在内存中
HSSFSheet sheet = wb.createSheet();
// 设置报表头样式
CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式
// 字段名所在表格的宽度
int ints = 5000 ;
// 设置表头样式
ExcelFormatUtil.initTitleEX(sheet, header, strs, ints );
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
Map<String , Object> map = list.get(i);
HSSFRow row = sheet.createRow(i + 1);
int j = 0;
HSSFCell cell = null;
for(int o = 0 ; o < map.size() ; o ++ ){
cell = row.createCell(j++);
cell.setCellValue(toString(map.get(zds[o])));
cell.setCellStyle(content);
}
}
}
try {
output = new ByteArrayOutputStream();
wb.write(output);
inputStream1 = new ByteArrayInputStream(output.toByteArray());
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
if (inputStream1 != null) {
inputStream1.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return inputStream1;
}
/*
*
* strs 表头
* */
public static InputStream export(List<List<Excel>> list , String[] strs) {
ByteArrayOutputStream output = null;
InputStream inputStream1 = null;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
BufferedImage bufferImg = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
// 设置报表头样式
CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式
// 字段名所在表格的宽度
int ints = 5000 ;
// 设置表头样式
ExcelFormatUtil.initTitleEX(sheet, header, strs, ints );
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
List<Excel> excels = list.get(i);
HSSFRow row = sheet.createRow(i + 1);
int j = 0;
HSSFCell cell = null;
for(Excel e : excels){
cell = row.createCell(j++);
cell.setCellStyle(content);
switch (e.getType()){
case "string":
cell.setCellValue(toString(e.getValue()));
break;
case "img":
if(e.getValue() != null && !e.getValue().equals("")){
try {
cell.setCellStyle(content);
row.setHeight((short) 1500);
String name = e.getValue().toString().split("/")[e.getValue().toString().split("/").length-1];
String filePath = "/www/server/webapps/upload/uploads/"+name;
System.out.println(filePath);
bufferImg = ImageIO.read(new File(filePath));
ImageIO.write(bufferImg, "jpg", byteArrayOut);
//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
//anchor主要用于设置图片的属性
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) (j-1), (i+1), (short) (j-1), (i+1));
anchor.setAnchorType(3);
//插入图片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
} catch (IOException Exception) {
Exception.printStackTrace();
}
}else{
cell.setCellValue("");
}
break;
default:
}
}
}
}
try {
output = new ByteArrayOutputStream();
wb.write(output);
inputStream1 = new ByteArrayInputStream(output.toByteArray());
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
if (inputStream1 != null) {
inputStream1.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return inputStream1;
}
/**
* 下载文件,纯SpringMVC的API来完成
*
* @param is 文件输入流
* @param name 文件名称,带后缀名
*
* @throws Exception
*/
public static ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
HttpHeaders header = new HttpHeaders();
String fileSuffix = name.substring(name.lastIndexOf('.') + 1);
fileSuffix = fileSuffix.toLowerCase();
Map<String, String> arguments = new HashMap<String, String>();
arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
arguments.put("xls", "application/vnd.ms-excel");
String contentType = arguments.get(fileSuffix);
header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));
if(is!=null && is.available()!=0){
header.add("Content-Length", String.valueOf(is.available()));
header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
byte[] bs = IOUtils.toByteArray(is);
return new ResponseEntity<>(bs, header, HttpStatus.OK);
}else{
String string="数据为空";
header.add("Content-Length", "0");
header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
}
}
public static String toString(Object val){
return val != null && !val.equals("") ? val.toString() : "";
}
}
controller代码
public ResponseEntity<byte[]> Export(User user, Date minsj , Date maxsj){
List<User> list = userService.selectByExample(user,null,null);
List<List<Excel>> map = new LinkedList<>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(User u : list){
u = userService.getId(u.getId());
List<Excel> m = new LinkedList<>();
m.add(new Excel("nicheng",u.getNicheng(),"string"));
m.add(new Excel("name",u.getName(),"string"));
map.add(m);
}
//Excel标题
String [] title = new String[]{"用户昵称","姓名"};
try {
return BaseFrontController.buildResponseEntity(ExportTools.export(map,title),System.currentTimeMillis()+".xls");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}