工具类方法
/**
* [导出excel]
*
* @param <T>
* @param excelHeader
* 表头
* @param excelHeadKey
* 字段名
* @param valueList
* List<HashMap>格式数据
* @return
*/
public static <T> HSSFWorkbook exportExcel(String[] excelHeader, String[] excelHeadKey, List<T> valueList) {
// 基本变量初始化
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("sheet1");
HSSFRow headerRow = hssfSheet.createRow(0);
HSSFCellStyle headCellStyle = hssfWorkbook.createCellStyle();
HSSFCellStyle dataCellStyle = hssfWorkbook.createCellStyle();
int columnNum = excelHeader.length;
// 样式设置
headCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headCellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
headCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
dataCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
dataCellStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
dataCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
dataCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
dataCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
dataCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
dataCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerRow.setHeightInPoints(20);
HSSFFont font = hssfWorkbook.createFont();
font.setFontHeightInPoints((short) 12);
headCellStyle.setFont(font);
// 打印表头
for (int i = 0; i < columnNum; i++) {
HSSFCell headerCell = headerRow.createCell(i);
headerCell.setCellValue(excelHeader[i]);
headerCell.setCellStyle(headCellStyle);
// 根据表头长度设置单元格宽度
hssfSheet.setColumnWidth(i, excelHeader[i].getBytes().length * 2 * 180);
}
HSSFRichTextString richString=null;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher=null;
Class tCls=null;
Method getMethod=null;
Object value=null;
String textValue=null;
String getMethodName=null;
T t = null;
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
// 打印数据行
for (int i = 0; i < valueList.size(); i++) {
HSSFRow dataRow = hssfSheet.createRow(i + 1);
dataRow.setHeightInPoints(20);
for (int j = 0; j < excelHeader.length; j++) {
HSSFCell cell = dataRow.createCell(j);
getMethodName = "get" + excelHeadKey[j].substring(0, 1).toUpperCase() + excelHeadKey[j].substring(1);
t=(T)valueList.get(i);
tCls = t.getClass();
try {
getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(t, new Object[] {});
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
cell.setCellStyle(dataCellStyle);
}
}
return hssfWorkbook;
}
package cn.com.lingnan.utils;
import java.io.IOException;
import java.net.URLEncoder;
import sun.misc.BASE64Encoder;
public class FileUtils {
/**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public static String encodeDownloadFilename(String filename, String agent)
throws IOException {
if (agent.contains("Firefox")) { // 火狐浏览器
filename = "=?UTF-8?B?"
+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
+ "?=";
filename = filename.replaceAll("\r\n", "");
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+"," ");
}
return filename;
}
}
具体实现
@RequestMapping("/exportXls")
public void exportXls(HttpSession httpSession,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException{
List<Subarea> list = subareaService.findAll();
String[] excelHeader={"分区编号","所属定区编号","所属区域编号","关键词","位置","开始编号",
"结束编号","单双号(0单双号,1单号,2双号)"};
String[] excelHeadKey={"id","decidedzoneId","regionId","addresskey","position","startnum",
"endnum","single"};
HSSFWorkbook workbook = POIUtil.exportExcel(excelHeader, excelHeadKey, list);
//第三步:使用输出流进行文件下载(一个流、两个头)
String filename = "分区数据.xls";
String contentType =httpSession.getServletContext().getMimeType(filename);
ServletOutputStream out = httpServletResponse.getOutputStream();
httpServletResponse.setContentType(contentType);
//获取客户端浏览器类型
String agent =httpServletRequest.getHeader("User-Agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
httpServletResponse.setHeader("content-disposition", "attachment;filename="+filename);
workbook.write(out);
}