springmvc+poi把数据导出Excel表
springmvc+pol把数据导出Excel表的步骤:
1.在pom.xml中先加poi的依赖包:
<!--导出excel需要的包--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
2.编码:
导入导出Excel工具类:ExcelUtil.Class
package net.stxy.one.utils; import net.stxy.one.poi.ExcelBean; import org.apache.http.client.utils.DateUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Excel导入导出工具类 * Created by ASUS on 2018/5/20 * * @Authod Grey Wolf */ public class ExcelUtil { private final static String excel2003L =".xls"; //2003- 版本的excel private final static String excel2007U =".xlsx"; //2007+ 版本的excel /** * Excel导入 */ public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{ List<List<Object>> list = null; //创建Excel工作薄 Workbook work = getWorkbook(in,fileName); if(null == work){ throw new Exception("创建Excel工作薄为空!"); } Sheet sheet = null; Row row = null; Cell cell = null; list = new ArrayList<List<Object>>(); //遍历Excel中所有的sheet for (int i = 0; i < work.getNumberOfSheets(); i++) { sheet = work.getSheetAt(i); if(sheet==null){continue;} //遍历当前sheet中的所有行 //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部 for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) { //读取一行 row = sheet.getRow(j); //去掉空行和表头 if(row==null||row.getFirstCellNum()==j){continue;} //遍历所有的列 List<Object> li = new ArrayList<Object>(); for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) { cell = row.getCell(y); li.add(getCellValue(cell)); } list.add(li); } } return list; } /** * 描述:根据文件后缀,自适应上传文件的版本 */ public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{ Workbook wb = null; String fileType = fileName.substring(fileName.lastIndexOf(".")); if(excel2003L.equals(fileType)){ //2003- wb = new HSSFWorkbook(inStr); }else if(excel2007U.equals(fileType)){ //2007+ wb = new XSSFWorkbook(inStr); }else{ throw new Exception("解析的文件格式有误!"); } return wb; } /** * 描述:对表格中数值进行格式化 */ public static Object getCellValue(Cell cell){ Object value = null; //格式化字符类型的数字 DecimalFormat df = new DecimalFormat("0"); //日期格式化 SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //格式化数字 DecimalFormat df2 = new DecimalFormat("0.00"); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if("General".equals(cell.getCellStyle().getDataFormatString())){ value = df.format(cell.getNumericCellValue()); }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){ value = sdf.format(cell.getDateCellValue()); }else{ value = df2.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: value = ""; break; default: break; } return value; } /** * 导入Excel表结束 * 导出Excel表开始 * @param sheetName 工作簿名称 * @param clazz 数据源model类型 * @param objs excel标题列以及对应model字段名 * @param map 标题列行数以及cell字体样式 */ public static XSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<ExcelBean>> map, String sheetName) throws IllegalArgumentException,IllegalAccessException,InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException { // 创建新的Excel工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称 XSSFSheet sheet = workbook.createSheet(sheetName); // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析; //字体样式 createFont(workbook); //创建标题(头) createTableHeader(sheet, map); //创建内容 createTableRows(sheet, map, objs, clazz); return workbook; } private static XSSFCellStyle fontStyle; private static XSSFCellStyle fontStyle2; public static void createFont(XSSFWorkbook workbook) { // 表头 fontStyle = workbook.createCellStyle(); XSSFFont font1 = workbook.createFont(); font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font1.setFontName("黑体"); // 设置字体大小 font1.setFontHeightInPoints((short) 14); fontStyle.setFont(font1); // 下边框 fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 左边框 fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 上边框 fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 右边框 fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 居中 fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 内容 fontStyle2=workbook.createCellStyle(); XSSFFont font2 = workbook.createFont(); font2.setFontName("宋体"); // 设置字体大小 font2.setFontHeightInPoints((short) 10); fontStyle2.setFont(font2); // 下边框 fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 左边框 fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 上边框 fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN); // 右边框 fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN); // 居中 fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); } /** * 根据ExcelMapping 生成列头(多行列头) * * @param sheet 工作簿 * @param map 每行每个单元格对应的列头信息 */ public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) { //cell起始位置 int startIndex=0; //cell终止位置 int endIndex=0; for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) { XSSFRow row = sheet.createRow(entry.getKey()); List<ExcelBean> excels = entry.getValue(); for (int x = 0; x < excels.size(); x++) { //合并单元格 if(excels.get(x).getCols()>1){ if(x==0){ endIndex+=excels.get(x).getCols()-1; CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex); sheet.addMergedRegion(range); startIndex+=excels.get(x).getCols(); }else{ endIndex+=excels.get(x).getCols(); CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex); sheet.addMergedRegion(range); startIndex+=excels.get(x).getCols(); } XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols()); // 设置内容 cell.setCellValue(excels.get(x).getHeadTextName()); if (excels.get(x).getCellStyle() != null) { // 设置格式 cell.setCellStyle(excels.get(x).getCellStyle()); } cell.setCellStyle(fontStyle); }else{ XSSFCell cell = row.createCell(x); // 设置内容 cell.setCellValue(excels.get(x).getHeadTextName()); if (excels.get(x).getCellStyle() != null) { // 设置格式 cell.setCellStyle(excels.get(x).getCellStyle()); } cell.setCellStyle(fontStyle); } } } } public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException, ClassNotFoundException, ParseException { int rowindex = map.size(); int maxKey = 0; List<ExcelBean> ems = new ArrayList<>(); for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) { if (entry.getKey() > maxKey) { maxKey = entry.getKey(); } } ems = map.get(maxKey); List<Integer> widths = new ArrayList<Integer>(ems.size()); for (Object obj : objs) { XSSFRow row = sheet.createRow(rowindex); for (int i = 0; i < ems.size(); i++) { ExcelBean em = (ExcelBean) ems.get(i); // 获得get方法 PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz); Method getMethod = pd.getReadMethod(); Object rtn = getMethod.invoke(obj); String value = ""; // 如果是日期类型进行转换 if (rtn != null) { if (rtn instanceof Date) { value = DateUtils.formatDate((Date)rtn,"yyyy-MM-dd"); } else if(rtn instanceof BigDecimal){ NumberFormat nf = new DecimalFormat("#,##0.00"); value=nf.format((BigDecimal)rtn).toString(); } else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){ value="--"; }else { value = rtn.toString(); } } XSSFCell cell = row.createCell(i); cell.setCellValue(value); cell.setCellType(XSSFCell.CELL_TYPE_STRING); cell.setCellStyle(fontStyle2); // 获得最大列宽 int width = value.getBytes().length * 300; // 还未设置,设置当前 if (widths.size() <= i) { widths.add(width); continue; } // 比原来大,更新数据 if (width > widths.get(i)) { widths.set(i, width); } } rowindex++; } // 设置列宽 for (int index = 0; index < widths.size(); index++) { Integer width = widths.get(index); width = width < 2500 ? 2500 : width + 300; width = width > 10000 ? 10000 + 300 : width + 300; sheet.setColumnWidth(index, width); } } }
用到的bean:ExcelBean,ExcelClass
package net.stxy.one.poi; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import java.io.Serializable; /** * Excel表格 * Created by ASUS on 2018/5/20 * * @Authod Grey Wolf */ public class ExcelBean implements Serializable { //列头(标题)名 private String headTextName; //对应字段名 private String propertyName; //合并单元格数 private Integer cols; //样式 private XSSFCellStyle cellStyle; public ExcelBean(){ } public ExcelBean(String headTextName, String propertyName){ this.headTextName = headTextName; this.propertyName = propertyName; } public ExcelBean(String headTextName, String propertyName, Integer cols) { super(); this.headTextName = headTextName; this.propertyName = propertyName; this.cols = cols; } public String getHeadTextName() { return headTextName; } public void setHeadTextName(String headTextName) { this.headTextName = headTextName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public Integer getCols() { return cols; } public void setCols(Integer cols) { this.cols = cols; } public XSSFCellStyle getCellStyle() { return cellStyle; } public void setCellStyle(XSSFCellStyle cellStyle) { this.cellStyle = cellStyle; } }
package net.stxy.one.poi; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Excel表格对应的表头信息处理类 * Created by ASUS on 2018/6/11 * * @Authod Grey Wolf */ public class ExcelClass { public Map<Integer,List<ExcelBean>> contentExcel(){ List<ExcelBean> excel=new ArrayList<>(); Map<Integer,List<ExcelBean>> map=new LinkedHashMap<>(); XSSFWorkbook xssfWorkbook=null; //设置标题栏 excel.add(new ExcelBean("序号","id",0)); excel.add(new ExcelBean("用户id","userid",0)); excel.add(new ExcelBean("分享内容","content",0)); excel.add(new ExcelBean("点赞数","nice",0)); excel.add(new ExcelBean("创建时间","createtime",0)); excel.add(new ExcelBean("图片1","pic1",0)); excel.add(new ExcelBean("图片2","pic2",0)); excel.add(new ExcelBean("图片3","pic3",0)); map.put(0, excel); return map; } }接口服务层service:
package net.stxy.one.service; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; /** * Created by ASUS on 2018/5/20 * * @Authod Grey Wolf */ public interface ExcelService { /** * 导出Excel表格 * @param salaryDate * @return * @throws InvocationTargetException * @throws ClassNotFoundException * @throws IntrospectionException * @throws ParseException * @throws IllegalAccessException */ XSSFWorkbook exportExcelInfo(String salaryDate) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException; }
接口服务实现层serviceImpl:
package net.stxy.one.service.impl; import net.stxy.one.mapper.ContentMapper; import net.stxy.one.model.Content; import net.stxy.one.poi.ExcelBean; import net.stxy.one.poi.ExcelClass; import net.stxy.one.service.ExcelService; import net.stxy.one.utils.ExcelUtil; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Excel实现类 * Created by ASUS on 2018/5/20 * * @Authod Grey Wolf */ @Service("excelService") public class ExcelServiceImpl implements ExcelService { @Autowired private ContentMapper contentMapper; @Override public XSSFWorkbook exportExcelInfo(String salaryDate) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException { //根据条件查询数据,把数据装载到一个list中 List<Content> list =contentMapper.selectAll(); List<ExcelBean> excel=new ArrayList<>(); Map<Integer,List<ExcelBean>> map=new ExcelClass().contentExcel(); XSSFWorkbook xssfWorkbook=null; String sheetName = salaryDate + "分享内容"; //调用ExcelUtil的方法 xssfWorkbook = ExcelUtil.createExcelFile(Content.class, list, map, sheetName); return xssfWorkbook; } }
控制层controller:
package net.stxy.one.controller; import com.google.gson.JsonObject; import net.stxy.one.model.Content; import net.stxy.one.service.ExcelService; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.beans.IntrospectionException; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Excel控制器 * Created by ASUS on 2018/5/20 * * @Authod Grey Wolf */ @Controller public class ExcelController { @Autowired private ExcelService excelService; @RequestMapping("/exports") public void export(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException { System.out.println("excel导出开始"); String salaryDate="1"; System.out.println("list:"+salaryDate); if(salaryDate!=""){ response.reset(); //清除buffer缓存 Map<String,Object> map=new HashMap<String,Object>(); System.out.println("文件名:"); // 指定下载的文件名 response.setHeader("Content-Disposition", "attachment;filename="+salaryDate+".xlsx"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); XSSFWorkbook workbook=null; //导出Excel对象 workbook = excelService.exportExcelInfo(salaryDate); OutputStream output; try { output = response.getOutputStream(); BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output); bufferedOutPut.flush(); workbook.write(bufferedOutPut); bufferedOutPut.close(); } catch (IOException e) { e.printStackTrace(); } } } }前端页面:
点击导出按钮:
<a class="layui-btn" href="<%=request.getContextPath()%>/exports">导出</a
显示效果:
打开Excel显示下载的数据:
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。