import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 导出Excel窗口
*/
public class ObjectExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String fileName = (String) model.get("fileName");
String sheetName = (String) model.get("sheetName");
List<String> titles = (List<String>) model.get("titles");
List<Map<String, String>> varList = (List<Map<String, String>>) model.get("varList");
if (StringUtils.isBlank(fileName)) {
fileName = DateUtils.getDate("yyyyMMddHHmmss");
}
if (StringUtils.isBlank(sheetName)) {
sheetName = "sheet1";
}
HSSFSheet sheet;
HSSFCell cell;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
sheet = workbook.createSheet(sheetName);
int len = titles.size();
HSSFCellStyle headerStyle = workbook.createCellStyle();
//居中
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//垂直
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//标题字体
HSSFFont headerFont = workbook.createFont();
//字体加粗
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 11);
headerStyle.setFont(headerFont);
short width = 20, height = 25 * 20;
sheet.setDefaultColumnWidth(width);
for (int i = 0; i < len; i++) {
//设置标题
String title = titles.get(i);
cell = getCell(sheet, 0, i);
cell.setCellStyle(headerStyle);
setText(cell, title);
}
sheet.getRow(0).setHeight(height);
//内容样式
HSSFCellStyle contentStyle = workbook.createCellStyle();
//居中
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
int varCount = varList.size();
for (int i = 0; i < varCount; i++) {
Map<String, String> vpd = varList.get(i);
for (int j = 0; j < len; j++) {
String varstr = vpd.get("var" + (j + 1)) != null ? vpd.get("var" + (j + 1)) : "";
cell = getCell(sheet, i + 1, j);
cell.setCellStyle(contentStyle);
setText(cell, varstr);
}
}
}
}
ObjectExcelView,EXCEL导出工具类,使用于POI-3.13版本
最新推荐文章于 2021-07-01 00:00:24 发布