SpringMVC poi Excel導出

mevan配置:java

<dependency>
  <groupId>org.apache.poi</groupId>   <artifactId>poi</artifactId> </dependency>

SpringMVC配置文件:web

spring-web-mvc.xmlspring

<bean id="execelViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
  <property name="order" value="1"/>
  <property name="basename" value="views"/>
</bean>

views. properties:apache

# 視圖配置文件(不添加後綴)
xls.assess.debit.(class)=cn.rst.hms.xls.view.AssessExcelView
# Excel模板(不添加後綴 .xls) xls.assess.debit.url=/WEB-INF/xls/AssessDebit

                  

 

  AssessDebit.xls:mvc

 

  Controller:app

  /**
     * 導出保養Excel報表
     * @param fromDate
     * @param toDate
     * @return
     */
    @RequestMapping(value = "/*******", method = RequestMethod.POST)
    public ModelAndView exportAssessDebit(
            @DateTimeFormat(pattern = Constants.DATE_FORMAT_YMD) Date fromDate,
            @DateTimeFormat(pattern = Constants.DATE_FORMAT_YMD) Date toDate) {
        Pagination<AssessDTO> data = assessService.loadEtaAssessDebit(fromDate, toDate);
        if (null == data) {
            return new ModelAndView("no-data");
        }
     // new ModelAndView("與view.properties中對應,解析得到模板與視圖").addObject("data", data);
return new ModelAndView("xls.assess.debit").addObject("data", data); }

 

Service:ide

  /**
     * 保養Excel數據封裝
     * @param fromDate
     * @param toDate
     * @return
     */
    public Pagination<AssessDTO> loadEtaAssessDebit(Date fromDate, Date toDate){
        log.info("統計考覈扣款: fromDate={}, toDate={}", fromDate, toDate);

        if (null == fromDate) {    // 若是開始時間爲空,默認設爲當月第一天而且最小值
            log.debug("報表:開始時間爲空,默認爲當月第一天");
            fromDate = DateTime.now().dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate();
        } else {    // 若是不爲空,設爲fromDate的最小值
            fromDate = new DateTime(fromDate).millisOfDay().withMinimumValue().toDate();
        }
        if (null == toDate) {    // 若是結束事件爲空,設爲當天並最大值
            log.debug("報表:結束時間爲空,默認爲當天。");
            toDate = DateTime.now().millisOfDay().withMaximumValue().toDate();
        } else {    // 若是不爲空,設爲toDate的最大值
            toDate = new DateTime(toDate).millisOfDay().withMaximumValue().toDate();
        }

        List<AssessDTO> assesses = loadAssessDebit(fromDate, toDate);
        if (assesses.size() < 0){
            log.info("查詢結果爲空", fromDate, toDate);
            return null;
        }

        Pagination<AssessDTO> pagination = new Pagination<>();
        Double totalMoney = 0d;

        for (AssessDTO assess : assesses) {
            pagination.getRows().add(assess);
            totalMoney += (assess.getMoney() == null ? 0 : assess.getMoney());
        }
        Map<String, Object> total = new HashedMap();
        total.put("totalMoney", totalMoney);
        pagination.getFooter().add(total);
        pagination.getExtras().put("fromDate", new DateTime(fromDate).toString(Constants.DATE_FORMAT_YMD));
        pagination.getExtras().put("toDate", new DateTime(toDate).toString(Constants.DATE_FORMAT_YMD));

        return pagination;
    }

 

AssessDebitExcelView:ui

package cn.rst.hms.xls.view;

import cn.rst.hms.common.constants.Constants;
import cn.rst.hms.core.dto.AssessDTO;
import cn.rst.hms.core.dto.Pagination;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Slf4j
public class AssessDebitExcelView extends AbstractExcelView{

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
                                      HSSFWorkbook workbook, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        Pagination<AssessDTO> data = (Pagination<AssessDTO>) model.get("data");

        log.info("生成保養表……, data = {}", data);

        String fromDate = (String) data.getExtras().get("fromDate");
        String toDate = (String) data.getExtras().get("toDate");

        // 設置報表文件名
        String excelName = "保養表".concat("-").concat(fromDate).concat("至").concat(toDate).concat(Constants.XLS_SUFFIX);
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(excelName.getBytes("gb2312"), "iso8859-1"));

        HSSFSheet sheet = workbook.getSheetAt(0);

        // 設置報表時間
        HSSFCell dateCell = super.getCell(sheet, 3, 0);
        super.setText(dateCell, "考覈時間區間: ".concat(fromDate.concat("至").concat(toDate)));

        List<AssessDTO> assesses = data.getRows();
        int row = 5;
        for (AssessDTO assess : assesses) {

            if (null != assess.getChapter()) {
                // 章次
                HSSFCell cell = super.getCell(sheet, row, 0);
                cell.setCellValue(assess.getChapter().getNumber());
                // 項目
                cell = super.getCell(sheet, row, 1);
                cell.setCellValue(assess.getChapter().getName());
            }

            // 考覈分數
            if (null != assess.getScore()) {
                HSSFCell cell = super.getCell(sheet, row, 3);
                cell.setCellValue(assess.getScore());
            }

            // 考覈總分
            if (null != assess.getBaseScore()) {
                HSSFCell cell = super.getCell(sheet, row, 4);
                cell.setCellValue(assess.getBaseScore().getScore());
            }

            // 考覈金額
            if (null != assess.getMoney()) {
                HSSFCell cell = super.getCell(sheet, row, 5);
                cell.setCellValue(assess.getMoney());
            }

            row++;
        }

        Map<String, Object> total = data.getFooter().get(0);

        if (null != total.get("totalMoney")) {
            HSSFCell cell = super.getCell(sheet, 21, 5);
            cell.setCellValue(String.valueOf(total.get("totalMoney").toString()));
            row++;
        }

        // 填報日期
        String date = DateTime.now().toString(Constants.DATE_FORMAT_YMD);
        HSSFCell cellOfDate = super.getCell(sheet, 25, 6);
        cellOfDate.setCellValue("報表時間: ".concat(date));
    }
}
相關文章
相關標籤/搜索