1.pom中添加依赖
<!-- 数据导出Excle依赖-->
<!-- 官网:http://poi.apache.org/index.html-->
<!-- API:http://poi.apache.org/apidocs/4.1/-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
2.创建ExportExcel工具类
//fieList为表头数据 getMessAboutExcle为数据库中查询后的结果
public HSSFWorkbook exportExcel(List<FieldParameter> fieList,List<Map<String, Object>> getMessAboutExcle)
{
//实例化Excel表格
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建第一个Sheet页
HSSFSheet sheet = workbook.createSheet("第一个Sheet页");
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 创建一个居中格式
style.setAlignment(HorizontalAlignment.CENTER);
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
//向标题行中插入列
for (short i = 0; i < fieList.size(); i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
// fieList.get(i).getfFieldNameCn() : 表头名
HSSFRichTextString text = new HSSFRichTextString(fieList.get(i).getfFieldNameCn());
cell.setCellValue(text);
}
//创建行,并向其中插入数据
for(short s = 0 ; s < getMessAboutExcle.size() ; s++){
row = sheet.createRow(s + 1);
for(short t = 0;t<fieList.size();t++){
HSSFCell cell = row.createCell(t);
cell.setCellStyle(style);
String en = fieList.get(t).getfFieldNameEn();
cell.setCellValue(getMessAboutExcle.get(s).get(en).toString());
}
}
return workbook;
}
3.引用
@ResponseBody
@RequestMapping("/downloadExporExcle")
public void downloadExporExcle(HttpServletResponse response) {
.......
ExportExcel export = new ExportExcel();
HSSFWorkbook hs = export.exportExcel(fieList, getMessAboutExcle);
try {
// 清空response
response.reset();
// 设置response的Header,设置下载文件名,如此处理防止中文乱码
response.setHeader("Content-Disposition", "inline;fileName=\"" + new String((layerparame.getpNameCn() + ".xls").getBytes("utf-8"),"ISO8859-1") + "\"");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
OutputStream os = response.getOutputStream();
hs.write(os);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}