首先引入依賴(低版本和高版本設置樣式的時候會有區別)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
創建ExcelUtils工具類
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author wyc
* @date 2019/8/2 14:20
*/
public class ExcelUtils {
private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
private static final int PAGE_NUM = 50;
//導出excle
public void exportExcle(HttpServletResponse response, String fileName, List<Map<String, Object>> list) {
//標題名字
String[] title = {"主鍵", "權限", "描述", "插入時間", "是否可用", "父節點", "權限類型", "是否顯示"};
OutputStream os = null;
HSSFWorkbook workBook = null;
try {
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(fileName + "__");
sbBuffer.append(doDate2String(new Date()));
sbBuffer.append(".xls");
String finallyFileName = sbBuffer.toString();
os = response.getOutputStream();
//設置響應頭
setResponseHeader(response, finallyFileName);
//生成workBook
workBook = getHSSFWorkbook(list, title);
workBook.write(os);
} catch (IOException e) {
logger.error("", e);
} finally {
try {
if (workBook != null) {
workBook.close();
}
} catch (IOException e) {
logger.error("", e);
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
logger.error("", e);
}
}
}
/**
* 獲取工作簿
*
* @param list
* @param columnMap
* @return
* @throws Exception
*/
public HSSFWorkbook getHSSFWorkbook(List<Map<String, Object>> list, String[] excelHeader) {
HSSFWorkbook wb = new HSSFWorkbook();
//對集合進行非空判斷
if (isEmptyOrNull(list) || isEmptyOrNull(excelHeader)) {
wb.createSheet();
return wb;
}
int pageNum = PAGE_NUM;//每頁數量
int size = list.size();//數據數量
int pages = (size % pageNum > 0) ? (size / pageNum + 1) : (size / pageNum);//導出頁數
// HSSFCellStyle cellStyle = null;//單元格樣式
HSSFSheet sheet = null;//頁面
/* HSSFFont font = wb.createFont();//字體
font.setFontHeightInPoints((short) 11);//設置字號
cellStyle = wb.createCellStyle();
cellStyle.setFont(font);
// cellStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
cellStyle.setFillPattern(FillPatternType.FINE_DOTS);*/
HSSFRow row = null;//單元格行
Map<String, Object> dataMap = null;
for (int j = 0; j < pages; j++) {
sheet = wb.createSheet();
//設置sheet的名字
wb.setSheetName(j, (String.valueOf((j + 1))));
//設置列寬
columnWidthSet(sheet, size);
//創建行
row = sheet.createRow(0);
//設置行高
// row.setHeight((short) 500);
//設置表頭
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHeader[i]);
cell.setCellStyle(getTopStyle(wb));
}
//填充數據
for (int i = pageNum * j; i < pageNum * j + pageNum && i < size; i++) {
//表頭佔幾行,填充數據時就從後面開始填充,後面加的1就是代表表頭佔幾行,佔幾行就加幾
row = sheet.createRow(i - pageNum * j + 1);
//設置行高
// row.setHeight((short) 500);
//獲取單元格樣式
HSSFCellStyle cellStyle = getStyle(wb);
Map<String, Object> map = list.get(i);
createCell(row, 0, map.get("id") == null ? "/" : map.get("id").toString(), cellStyle);
createCell(row, 1, map.get("permission") == null ? "/" : map.get("permission").toString(), cellStyle);
createCell(row, 2, map.get("description") == null ? "/" : map.get("description").toString(), cellStyle);
createCell(row, 3, map.get("insertDt") == null ? "/" : map.get("insertDt").toString(), cellStyle);
createCell(row, 4, map.get("available") == null ? "/" : map.get("available").toString(), cellStyle);
createCell(row, 5, map.get("pid") == null ? "/" : map.get("pid").toString(), cellStyle);
createCell(row, 6, map.get("type") == null ? "/" : map.get("type").toString(), cellStyle);
createCell(row, 7, map.get("showStatus") == null ? "/" : map.get("showStatus").toString(), cellStyle);
}
}
return wb;
}
/**
* 創建單元格
*
* @param row
* @param column
* @param value
* @param cellStyle
*/
private void createCell(HSSFRow row, int column, String value, CellStyle cellStyle) {
HSSFCell cell = row.createCell(column);
//設置單元格的值
cell.setCellValue(value);
if (cellStyle != null) {
//設置單元格的樣式
cell.setCellStyle(cellStyle);
}
}
//發送響應流方法
private void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
//TODO 處理異常
logger.error("", e);
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
//TODO 處理異常
logger.error("", ex);
}
}
/**
* 列寬設置
*/
private void columnWidthSet(HSSFSheet sheet, int size) {
for (int i = 0; i < size; i++) {
sheet.setColumnWidth(i, 5000);
}
}
/**
* 寬度設置,讓列寬隨着導出的列長自動適應(可能不能用)
*/
/*
private void columnWidthSet(HSSFSheet sheet, int size) {
// 讓列寬隨着導出的列長自動適應
for (int colNum = 0; colNum < size; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
// 當前行未被使用過
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == CellType.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 + 4) * 256);
}
}
}
*/
/**
* 列頭單元格樣式
*/
private HSSFCellStyle getTopStyle(HSSFWorkbook workbook) {
// 設置字體
HSSFFont font = workbook.createFont();
// 設置字體大小
font.setFontHeightInPoints((short) 11);
// 字體加粗
font.setBold(true);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式;
HSSFCellStyle style = workbook.createCellStyle();
// 設置底邊框;
style.setBorderBottom(BorderStyle.THIN);
// 設置底邊框顏色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
// 設置左邊框;
style.setBorderLeft(BorderStyle.THIN);
// 設置左邊框顏色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
// 設置右邊框;
style.setBorderRight(BorderStyle.THIN);
// 設置右邊框顏色;
style.setRightBorderColor(IndexedColors.BLACK.index);
// 設置頂邊框;
style.setBorderTop(BorderStyle.THIN);
// 設置頂邊框顏色;
style.setTopBorderColor(IndexedColors.BLACK.index);
// 在樣式用應用設置的字體;
style.setFont(font);
// 設置自動換行;
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HorizontalAlignment.CENTER);
// 設置垂直對齊的樣式爲居中對齊;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/**
* 列數據信息單元格樣式
*/
private HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 設置字體
HSSFFont font = workbook.createFont();
// 設置字體大小
// font.setFontHeightInPoints((short)10);
// 字體加粗
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式;
HSSFCellStyle style = workbook.createCellStyle();
// 設置底邊框;
style.setBorderBottom(BorderStyle.THIN);
// 設置底邊框顏色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
// 設置左邊框;
style.setBorderLeft(BorderStyle.THIN);
// 設置左邊框顏色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
// 設置右邊框;
style.setBorderRight(BorderStyle.THIN);
// 設置右邊框顏色;
style.setRightBorderColor(IndexedColors.BLACK.index);
// 設置頂邊框;
style.setBorderTop(BorderStyle.THIN);
// 設置頂邊框顏色;
style.setTopBorderColor(IndexedColors.BLACK.index);
// 在樣式用應用設置的字體;
style.setFont(font);
// 設置自動換行;
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HorizontalAlignment.CENTER);
// 設置垂直對齊的樣式爲居中對齊;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/**
* 將日期轉化爲String
*
* @param confirmDate
* @param patten
* @return
*/
public static String doDate2String(Date confirmDate, String... patten) {
if (confirmDate == null) {
return "";
}
SimpleDateFormat sdf = null;
if (patten == null || patten.length == 0) {
sdf = new SimpleDateFormat("yyyy-MM-dd");
} else {
sdf = new SimpleDateFormat(patten[0]);
}
return sdf.format(new Date(confirmDate.getTime()));
}
/**
* 非空判斷
*
* @param obj
* @return
*/
public boolean isEmptyOrNull(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
} else if (obj instanceof List) {
return ((List) obj).isEmpty();
}
return obj.toString().isEmpty();
}
}
controller層
import com.comvee.intelligentp.authority.model.po.AuthorityPO;
import com.comvee.intelligentp.authority.service.AuthorityService;
import com.comvee.intelligentp.common.wrapper.Result;
import com.comvee.intelligentp.export.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author wyc
* @date 2019/8/2 15:15
*/
@RestController
@RequestMapping("/web/testExport")
public class TestExportController {
@Autowired
private AuthorityService authorityService;
@RequestMapping("export")
public Result testExport(HttpServletResponse response){
//excle文檔的名字
String fileName = "數據導出";
//自己實現數據查詢
List<AuthorityPO> pos = this.authorityService.listAuthority(null, null, null);
//可以將數據封裝到map集合,也可以封裝到對象裏面(比如封裝到對象裏面就可以直接使用上面的集合pos傳參,工具類裏面要做相應的修改)
List<Map<String, Object>> list = new ArrayList<>();
if ( null != pos && pos.size() >0){
for (AuthorityPO po : pos) {
Map<String, Object> map = new HashMap<>();
map.put("id",po.getSid());
map.put("permission",po.getPermission());
map.put("description",po.getDescription());
map.put("insertDt",po.getInsertDt());
map.put("available",po.getAvailable());
map.put("pid",po.getPid());
map.put("type",po.getaType());
map.put("status",po.getShowStatus());
list.add(map);
}
}
ExcelUtils excelUtils = new ExcelUtils();
excelUtils.exportExcle(response,fileName,list);
return new Result("導出成功");
}
}