poi handles excel export

one minute explanation

本文主要针对利用poi组件导出excel方式进行说明。
涉及知识点:
 - poi组件
 - spring4.0知识 

poi component

  • style
CellStylecellStyle_topic_head = workbook.createCellStyle();
cellStyle_topic_head.setWrapText(true);//自动换行
cellStyle_topic_head.setAlignment(CellStyle.ALIGN_LEFT);//水平居中
cellStyle_topic_head.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
cellStyle_topic_head.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
cellStyle_topic_head.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
cellStyle_topic_head.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
cellStyle_topic_head.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 
sheet.getRow(NumberConstants.ZERO).setHeightInPoints(Float.valueOf("144.25"));//第一行的行高
  • Merge Cells

//第一行_第一个合并单元格
PoiUtil.setCellRangeAddressInfo(new CellRangeAddress(0, 0, 0, 1), workbook, cellStyle_data, sheet, "内容值");

//封装的方法
public static void setCellRangeAddressInfo(CellRangeAddress cellRangeAddress, Workbook workbook, CellStyle cellStyle, Sheet sheet, String value) {
    sheet.addMergedRegion(cellRangeAddress);
    PoiUtil.setBorder(1, cellRangeAddress, sheet, workbook);//边框
    Cell cell = sheet.getRow(cellRangeAddress.getFirstRow()).getCell(cellRangeAddress.getFirstColumn());
    cell.setCellStyle(cellStyle);
    cell.setCellValue(value);
}
  • Lock row and lock column
//锁行和锁列
sheet.createFreezePane(2, 4);
  • Chinese file name
//锁行和锁列
response.setHeader("Content-disposition", "attachment;filename=" + new String("报表名称".getBytes(),"iso-8859-1") + ".xls");  

spring4.0 knowledge


  • Rendering views and processing data

The controller code is as follows:

    /**
     * 表格导出
     * 
     * @return
     */
    @RequestMapping(value = "/downLoad", method = RequestMethod.GET)
    public ModelAndView downLoad(@Valid BaseDownloadDTO baseDownloadDTO, ModelMap model, HttpServletRequest request) {
        BaseDownloadVO baseDownloadVO = topicService.getDownLoadData(baseDownloadDTO);
        model.put("data", baseDownloadVO);
        return new ModelAndView(new TopicViewExcel(redisTemplate), model);  
    }

The view code is as follows:

public class TopicViewExcel extends AbstractXlsView {

    private RedisTemplate<String, Object> redisTemplate;

    public TopicViewExcel(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置数据 
        BaseDownloadVO baseDownloadVO = (BaseDownloadVO) model.get("data"); 
        //导出
        response.setHeader("Content-disposition", "attachment;filename=" + new String("专题数据报表".getBytes(),"iso-8859-1") + ".xls");     
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325997380&siteId=291194637