controller层
public JsonResponse exportData(HttpServletResponse response,
@RequestParam(name = "inventoryId", required = true) String inventoryId,
@RequestParam(name = "batch", required = true) Integer batch) {
try {
String fileName = "资源导出详情";
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
OutputStream os = response.getOutputStream();
List<Map<String,Object>> list = inventoryDetailService.selectMapByBatchId(inventoryId, batch);
List<Map<String, Object>> datalist = new ArrayList<>();
for(int i = 0; i< list.size();i++) {
Map<String, Object> m1 = list.get(i);
Map<String, Object> m2 = new LinkedHashMap<String, Object>();
m2.put("no", i+1);
m2.put("assetsName", m1.get("assetsName"));
m2.put("assetsCode", m1.get("assetsCode"));
m2.put("resourceName", m1.get("resourceName"));
m2.put("typeName", m1.get("typeName"));
m2.put("parentName", m1.get("parentName"));
m2.put("maintainUser", m1.get("maintainUser"));
m2.put("maintainMethod", m1.get("maintainMethod"));
m2.put("maintainTime", m1.get("maintainTime"));
m2.put("statusName", m1.get("statusName"));
m2.put("buyTime", m1.get("buyTime"));
datalist.add(m2);
}
String[] heads = new String[] {"序号", "资产名称", "资产编号", "资源名称", "资源类型", "父类型", "维保人", "联系方式", "维保时间", "资产状态", "采购时间"};
ExcelUtil.exportExcel(fileName, fileName, heads, datalist, os);
return okJson();
} catch (Exception e) {
e.printStackTrace();
return errorJson("资产导出失败!");
}
}```
工具类 ExcelUtil
```java
在这里插入代码片package com.moka.common.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName : ExcelUtil //类名
* @Description : 处理excel读取数据 //描述
*/
public class ExcelUtil {
/**
*
* 方法功能说明:
* 参数说明:
* @param sheetName sheet的名称
* @param title 报告的名称
* @param heads 报表的表头信息
* @param datalist 输出的数据源
* @param outPutStream 下载excel的输出流
*/
public static void exportExcel(String sheetName,String title,String[] heads,List<Map<String, Object>> datalist,OutputStream outPutStream) {
try {
if(sheetName == null) {
sheetName = "sheet0";
}
Workbook workBook = new XSSFWorkbook();
XSSFCellStyle titlesStyle = getTitleCellStyle(workBook);
XSSFCellStyle headerStyle = getHeardCellStyle(workBook);
XSSFCellStyle dataStyle = getDataCellStyle(workBook);
Sheet sheet = workBook.createSheet(sheetName);
int startCellIndex = 2;
int startRowIndex = 2;
int rowIndex = startRowIndex;
//Row row = sheet.createRow(rowIndex);//常见标题title
Cell cell = null;
int cellIndex = startCellIndex;
//2.创建head
rowIndex++;
Row row = sheet.createRow(rowIndex);//创建表头列
for(String head:heads) {
cell = row.createCell(cellIndex);
cell.setCellValue(head);
cell.setCellStyle(headerStyle);
cellIndex++;
}
rowIndex++;
//3.创建数据body
for(Map<String, Object> dataMap :datalist) {
row = sheet.createRow(rowIndex);
cellIndex = startCellIndex;
for(String key:dataMap.keySet()) {
cell = row.createCell(cellIndex);
cell.setCellValue(dataMap.get(key)==null?"":dataMap.get(key).toString());
cell.setCellStyle(dataStyle);
cellIndex ++;
}
rowIndex++;
}
//4.设置列宽自动自动适应
for(int i = startCellIndex ; i < heads.length+startCellIndex; i++) {
sheet.autoSizeColumn(i);
}
//处理中文不能自动调整列宽的问题
setSizeColumn((XSSFSheet)sheet, heads.length);
//1.设置标题
row = sheet.createRow(startRowIndex);
cellIndex = startCellIndex;
if(title != null) {
cell = row.createCell(cellIndex);
cell.setCellValue(title);
cell.setCellStyle(titlesStyle);
rowIndex ++;
}
workBook.write(outPutStream);
outPutStream.flush();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
outPutStream.flush();
outPutStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
// 自适应宽度(中文支持)
private static void setSizeColumn(XSSFSheet sheet, int size) {
for (int columnNum = 1; columnNum <= size + 1; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum < sheet.getLastRowNum() + 1; rowNum++) {
XSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
XSSFCell currentCell = currentRow.getCell(columnNum);
// if (currentCell.getCellTypeEnum() == CellType.STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
// }
}
}
}
sheet.setColumnWidth(columnNum,columnWidth>70? 70*256:columnWidth*256);
}
}
private static XSSFCellStyle getDataCellStyle(Workbook workBook) {
XSSFCellStyle cellStyle = (XSSFCellStyle) workBook .createCellStyle();// 创建标题样式
//对齐位置
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);//设置水平居中
//填充色
//XSSFColor color = new XSSFColor(Color.LIGHT_GRAY);
//cellStyle.setFillForegroundColor(color);
//cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//设置边框
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
cellStyle.setBorderTop(BorderStyle.THIN);//上边框
cellStyle.setBorderRight(BorderStyle.THIN);//右边框
cellStyle.setWrapText(true);//设置自动换行
//字体
XSSFFont headerFont = (XSSFFont) workBook.createFont(); //创建字体样式
headerFont.setBold(false);// 字体加粗
headerFont.setFontHeightInPoints((short) 10); //设置字体大小
cellStyle.setFont(headerFont); //为标题样式设置字体样式
return cellStyle;
}
private static XSSFCellStyle getTitleCellStyle(Workbook workBook) {
XSSFCellStyle headerStyle = (XSSFCellStyle) workBook .createCellStyle();// 创建标题样式
//对齐位置
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
headerStyle.setAlignment(HorizontalAlignment.LEFT);//设置水平居左
//字体
XSSFFont headerFont = (XSSFFont) workBook.createFont(); //创建字体样式
headerFont.setBold(true);// 字体加粗
headerFont.setFontHeightInPoints((short) 14); //设置字体大小
headerStyle.setFont(headerFont); //为标题样式设置字体样式
return headerStyle;
}
private static XSSFCellStyle getHeardCellStyle(Workbook workBook) {
XSSFCellStyle headerStyle = (XSSFCellStyle) workBook .createCellStyle();// 创建标题样式
//对齐位置
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
headerStyle.setAlignment(HorizontalAlignment.CENTER);//设置水平居中
//填充色
XSSFColor color = new XSSFColor(new java.awt.Color(255, 204, 153));
headerStyle.setFillForegroundColor(color);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//设置边框
headerStyle.setBorderBottom(BorderStyle.THIN); //下边框
headerStyle.setBorderLeft(BorderStyle.THIN);//左边框
headerStyle.setBorderTop(BorderStyle.THIN);//上边框
headerStyle.setBorderRight(BorderStyle.THIN);//右边框
//字体
XSSFFont headerFont = (XSSFFont) workBook.createFont(); //创建字体样式
headerFont.setBold(true);// 字体加粗
headerFont.setFontHeightInPoints((short) 12); //设置字体大小
headerStyle.setFont(headerFont); //为标题样式设置字体样式
return headerStyle;
}
public static List<Map<String, String>> readExcel(String fileName, InputStream inputStream, Integer num) {
List<Map<String, String>> list = new ArrayList<>();//存储数据
try {
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(num);// 获取第一个表格
Row titleRow = sheet.getRow(0);// 得到标题行
int lastRowNum = sheet.getLastRowNum();// 获取总行数
int lastCellNum = titleRow.getLastCellNum();//获取总列数
String key = null;
String msg = null;
Row row = null;
Cell rowcell = null;
Cell cell = null;
for (int i = 1; i <= lastRowNum; i++) {
Map<String, String> map = new LinkedHashMap<String, String>();
row = sheet.getRow(i);
map.put("行号", "" + (i + 1));
for (int j = 0; j < lastCellNum; j++) {
rowcell = titleRow.getCell(j);
if (rowcell == null) {
continue;
}
key = getCellValue(rowcell);// 得到列名
cell = row.getCell(j);
if (cell == null) {
continue;
}
msg = getCellValue(cell);// 得到列值
map.put(key, msg);
}
list.add(map);
}
workbook.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 方法功能说明:获取单元格的值
* POI读excel数据中的数字,读出的是double类型的数字,
* 精度不准确,比如4.96会读出4.9599997654,
* 因此对数字要进行保留2位小数的四舍五入(不处理日期格式)
*
* @param cell
* @return 作者:wangbb
* 创建时间:202-7-27 10:43:51
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
NumberFormat numberFormat = NumberFormat.getNumberInstance();
numberFormat.setGroupingUsed(false);//不分组,比如2001000不表示为2,001,000
numberFormat.setMaximumFractionDigits(2);//保留2位小数
numberFormat.setRoundingMode(RoundingMode.HALF_UP);//四合五入
if (cell==null) {
cellValue = "";
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cellValue = numberFormat.format(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getStringCellValue().trim();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
cellValue = numberFormat.format(cell.getNumericCellValue());
} else {
cellValue = "";
}
return cellValue;
}
private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
/**
* 导出Excel
*
* @param excelName 要导出的excel名称
* @param list 要导出的数据集合
* @param fieldMap 中英文字段对应Map,即要导出的excel表头
* @param response 使用response可以导出到浏览器
* @param <T>
*/
public static <T> void export(String excelName, List<T> list, LinkedHashMap<String, String> fieldMap, HttpServletResponse response) {
// 设置默认文件名为当前时间:年月日时分秒
if (excelName == null || excelName == "") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
try {
response.setHeader("Content-disposition", "attachment; filename="
+ new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
} catch (UnsupportedEncodingException e1) {
logger.info(e1.getMessage());
}
try {
//创建一个WorkBook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
HSSFSheet sheet = wb.createSheet(excelName);
//创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
//创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 填充工作表
fillSheet(sheet, list, fieldMap, style);
//将文件输出
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
logger.info("导出Excel失败!");
logger.error(e.getMessage());
}
}
/**
* 根据字段名获取字段对象
*
* @param fieldName 字段名
* @param clazz 包含该字段的类
* @return 字段
*/
public static Field getFieldByName(String fieldName, Class<?> clazz) {
logger.info("根据字段名获取字段对象:getFieldByName()");
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
//如果本类中存在该字段,则返回
if (field.getName().equals(fieldName)) {
return field;
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
//递归
return getFieldByName(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
* 根据字段名获取字段值
*
* @param fieldName 字段名
* @param o 对象
* @return 字段值
* @throws Exception 异常
*/
public static Object getFieldValueByName(String fieldName, Object o)
throws Exception {
logger.info("根据字段名获取字段值:getFieldValueByName()");
Object value = null;
//根据字段名得到字段对象
Field field = getFieldByName(fieldName, o.getClass());
//如果该字段存在,则取出该字段的值
if (field != null) {
field.setAccessible(true);//类中的成员变量为private,在类外边使用属性值,故必须进行此操作
value = field.get(o);//获取当前对象中当前Field的value
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 "
+ fieldName);
}
return value;
}
/**
* 根据带路径或不带路径的属性名获取属性值,即接受简单属性名,
* 如userName等,又接受带路径的属性名,如student.department.name等
*
* @param fieldNameSequence 带路径的属性名或简单属性名
* @param o 对象
* @return 属性值
* @throws Exception 异常
*/
public static Object getFieldValueByNameSequence(String fieldNameSequence,
Object o) throws Exception {
logger.info("根据带路径或不带路径的属性名获取属性值,即接受简单属性名:getFieldValueByNameSequence()");
Object value = null;
// 将fieldNameSequence进行拆分
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
// 根据数组中第一个连接属性名获取连接属性对象,如student.department.name
Object fieldObj = getFieldValueByName(attributes[0], o);
//截取除第一个属性名之后的路径
String subFieldNameSequence = fieldNameSequence
.substring(fieldNameSequence.indexOf(".") + 1);
//递归得到最终的属性对象的值
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
* 向工作表中填充数据
*
* @param sheet excel的工作表名称
* @param list 数据源
* @param fieldMap 中英文字段对应关系的Map
* @param style 表格中的格式
* @throws Exception 异常
*/
public static <T> void fillSheet(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap, HSSFCellStyle style) throws Exception {
logger.info("向工作表中填充数据:fillSheet()");
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充数组
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 填充表头
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
}
// 填充内容
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
row.createCell(i).setCellValue(fieldValue);
}
}
}
}