今天就再分享一种excel导出的方法
首先是添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
然后是控制层
import com.example.springboot08.com.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @Author: Administrator
* @Description:
* @Date: 2019-08-25 18:14
* @Modified By: excel导出
*/
@Controller
@RequestMapping("/ExportController")
public class ExportController {
private static final Logger logger = LoggerFactory.getLogger(ExportController.class);
private static final String dateFormat = "yyyy-MM-dd-HH-mm";
@RequestMapping("/excel")
@ResponseBody
public void excel(HttpServletRequest request, HttpSession session, HttpServletResponse response){
//HashMap paramMap= ControllerUtil.getParamMap(request);
List<HashMap<String,String>> resultMap=new ArrayList<HashMap<String,String>>();
HashMap<String,String> map1=new HashMap<String,String>();
HashMap<String,String> map2=new HashMap<String,String>();
HashMap<String,String> map3=new HashMap<String,String>();
map1.put("name","张三");
map1.put("age","23");
map1.put("sex","男");
map1.put("profession","java");
map1.put("WorkingLife","3");
map1.put("Rank","java中级开发工程师");
map2.put("name","李四");
map2.put("age","35");
map2.put("sex","男");
map2.put("profession","架构师");
map2.put("WorkingLife","10");
map2.put("Rank","高级架构师");
map3.put("name","李梅");
map3.put("age","25");
map3.put("sex","女");
map3.put("profession","H5工程师");
map3.put("WorkingLife","5");
map3.put("Rank","中级H5工程师");
resultMap.add(map1);
resultMap.add(map2);
resultMap.add(map3);
//调用导出方法
exprotExcel(resultMap,response);
}
public void exprotExcel(List<HashMap<String, String>> resultMap,
HttpServletResponse response){
//excel标题
String[] title={"姓名","年龄","性别","职位","工作年限","职级"};
//excel文件名称
Date nowTime=new Date();
SimpleDateFormat time=new SimpleDateFormat(dateFormat);
String excelName = "员工信息"+time.format(nowTime)+".xls";
//sheet名
String sheetName = "职员信息";
String[][] content = new String[resultMap.size()][title.length];
for (int i = 0; i <= resultMap.size()-1; i++) {
HashMap<String, String> map = resultMap.get(i);
content[i]=new String[title.length];
content[i][0]=map.get("name");
content[i][1]=map.get("age");
content[i][2]=map.get("sex");
content[i][3]=map.get("profession");
content[i][4]=map.get("WorkingLife");
content[i][5]=map.get("Rank");
}
//创建HSSFWorkbook文档
HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//响应信息到客户端
try {
this.setResponseHeader(response,excelName);
OutputStream os=response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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) {
ex.printStackTrace();
}
}
}
然后是工具方法 (重点)
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;
/**
* @Author: Administrator
* @Description:
* @Date: 2019-08-25 18:26
* @Modified By: excel导出工具类
*/
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
}
一个拼接前台参数的工具类(可有可无)
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author: Administrator
* @Description:
* @Date: 2019-08-25 18:17
* @Modified By: 拼接从前台接收的参数
*/
public class ControllerUtil {
/**
* 拼装列表返回结果
* @param total
* @param page
* @param pagesize
* @param jsonResult
* @return
*/
public static Map getReturnMap(int total,String page,String pagesize,String jsonResult){
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", String.valueOf(total));
map.put("page", String.valueOf(Integer.parseInt(page)*Integer.parseInt(pagesize)));
map.put("pagesize", pagesize);
map.put("rows", JSONArray.fromObject(jsonResult));
return map;
}
public static Map<String, Object> getReturnMapWithFooter(String jsonResult){
Map<String, Object> map = new ConcurrentHashMap<String, Object>();
map.put("rows", JSONArray.fromObject(jsonResult));
return map;
}
/**
* 拼接查询参数
* @param request
* @return
*/
public static HashMap getParamMap(HttpServletRequest request){
HashMap<String, String> paramMap = new HashMap<String, String>();
Enumeration<String> pNames=request.getParameterNames();
while(pNames.hasMoreElements()){
String name = (String)pNames.nextElement();
String value = request.getParameter(name);
if(name.equals("page")){
value = String.valueOf(Integer.parseInt(value)*10);
}
paramMap.put(name, value);
}
return paramMap;
}
/**
* 拼接查询参数
* @param request
* @return
*/
public static HashMap getParamsMap(HttpServletRequest request){
HashMap<String, String> paramMap = new HashMap<String, String>();
String pageSize = request.getParameter("pagesize");
Enumeration<String> pNames=request.getParameterNames();
while(pNames.hasMoreElements()){
String name = (String)pNames.nextElement();
String value = request.getParameter(name);
if(name.equals("page")){
value = String.valueOf(Integer.parseInt(value)*Integer.parseInt(pageSize));
}
paramMap.put(name, value);
}
return paramMap;
}
}