com.excel.ExcelView.java Source code

Java tutorial

Introduction

Here is the source code for com.excel.ExcelView.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.excel;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 *
 * @author Chilvas-PC
 */
public class ExcelView extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ExcelModel em = (ExcelModel) model.get("myModel");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + em.getFileName() + ".xls\"");

        HSSFSheet excelSheet = workbook.createSheet(em.getFileName());

        setExcelHeader(excelSheet, em.getTitles());
        setExcelRows(excelSheet, em.getContents());
    }

    public void setExcelHeader(HSSFSheet excelSheet, List titles) {
        HSSFRow excelHeader = excelSheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            excelHeader.createCell(i).setCellValue(titles.get(i).toString());
        }
    }

    public void setExcelRows(HSSFSheet excelSheet, List<List<String>> content) {
        int record = 1;
        for (List<String> row : content) {
            HSSFRow excelRow = excelSheet.createRow(record++);
            int cnt = 0;
            for (String value : row) {
                excelRow.createCell(cnt++).setCellValue(value);
            }
        }
    }

}