import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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;
import cn.com.spdbccc.luck.entity.Employee;
public class ViewExcel extends AbstractExcelView {
@Override
@SuppressWarnings("unchecked")
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String excelName = "中奖名单.xls";
// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(excelName, "UTF-8"));
List<Employee> empList = (List<Employee>) model.get("viewList");
// 产生Excel表头
HSSFSheet sheet = workbook.createSheet("employeeList");
HSSFRow header = sheet.createRow(0); // 第0行
// 产生标题列
header.createCell(0).setCellValue("Name");
header.createCell(1).setCellValue("Department");
header.createCell(2).setCellValue("Grade");
// 设置表头字体
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
header.getCell(0).setCellStyle(style);
header.getCell(1).setCellStyle(style);
header.getCell(2).setCellStyle(style);
sheet.autoSizeColumn(0); //调整第一列宽度
sheet.autoSizeColumn(1); //调整第二列宽度
sheet.autoSizeColumn(2); //调整第三列宽度
// header.createCell((short) 3).setCellValue("count");
// HSSFCellStyle cellStyle = workbook.createCellStyle();
// cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));
// 填充数据
int rowNum = 1;
String grade = "";
for (Iterator<Employee> iter = empList.iterator(); iter.hasNext();) {
Employee element = (Employee) iter.next();
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(element.getName());
row.createCell(1).setCellValue(element.getDepartment());
switch (element.getP_grade()) {
case "1":
grade = "一等奖";
break;
case "2":
grade = "二等奖";
break;
case "3":
grade = "三等奖";
break;
case "4":
grade = "四等奖";
break;
}
row.createCell(2).setCellValue(grade);
// row.getCell((short) 2).setCellStyle(cellStyle);
// row.createCell((short) 3).setCellValue(element.getCount());
}
// 列总和计算
// HSSFRow row = sheet.createRow(rowNum);
// row.createCell((short) 0).setCellValue("TOTAL:");
// String formual = "SUM(D2:D" + rowNum + ")"; // D2到D[rowNum]单元格起(count数据)
// row.createCell((short) 3).setCellFormula(formual);
}
}
由于springMVC暂不支持xlsx格式的导出,因此需要自己修改AbstractExcelView来实现
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.LocalizedResourceHelper;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractView;
public abstract class MyAbstractExcelView extends AbstractView {
/** The content type for an Excel response */
private static final String CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/** The extension to look for existing templates */
private static final String EXTENSION = ".xlsx";
private String url;
/** * Default Constructor. * Sets the content type of the view to "application/vnd.ms-excel". */
public MyAbstractExcelView() {
setContentType(CONTENT_TYPE);
}
public void setUrl(String url) {
this.url = url;
}
@Override
protected boolean generatesDownloadContent() {
return true;
}
/**
* Renders the Excel view, given the specified model.
*/
@Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Workbook workbook;
ByteArrayOutputStream baos = createTemporaryOutputStream();
/*if (this.url != null) {
workbook = getTemplateSource(this.url, request);
}
else {*/
workbook = new XSSFWorkbook();
logger.debug("Created Excel Workbook from scratch");
//}
buildExcelDocument(model, workbook, request, response);
// Set the content type.
//response.setContentType(getContentType());
// Should we set the content length here?
// response.setContentLength(workbook.getBytes().length);
// Flush byte array to servlet output stream.
//ServletOutputStream out = response.getOutputStream();
workbook.write(baos);
writeToResponse(response, baos);
//out.flush();
}
protected Workbook getTemplateSource(String url, HttpServletRequest request) throws Exception {
LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext());
Locale userLocale = RequestContextUtils.getLocale(request);
Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale);
// Create the Excel document from the source.
if (logger.isDebugEnabled()) {
logger.debug("Loading Excel workbook from " + inputFile);
}
//POIFSFileSystem fs = new POIFSFileSystem(inputFile.getInputStream());
return new XSSFWorkbook(inputFile.getInputStream());
}
protected abstract void buildExcelDocument(
Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response)
throws Exception;
protected Cell getCell(Sheet sheet, int row, int col) {
Row sheetRow = sheet.getRow(row);
if (sheetRow == null) {
sheetRow = sheet.createRow(row);
}
Cell cell = sheetRow.getCell(col);
if (cell == null) {
cell = sheetRow.createCell(col);
}
return cell;
}
protected void setText(Cell cell, String text) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(text);
}
}
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import cn.com.spdbccc.luck.entity.Employee;
//import com.hmkcode.view.abstractview.AbstractExcelView;
//import com.hmkcode.vo.Article;
public class MyExcelView extends MyAbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Sheet sheet = workbook.createSheet("sheet 1");
@SuppressWarnings("unchecked")
List<Employee> employees = (List<Employee>) model.get("viewList");
Row row = null;
Cell cell = null;
int r = 0;
int c = 0;
//Style for header cell
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
//Create header cells
row = sheet.createRow(r++);
cell = row.createCell(c++);
cell.setCellStyle(style);
cell.setCellValue("Title");
cell = row.createCell(c++);
cell.setCellStyle(style);
cell.setCellValue("URL");
cell = row.createCell(c++);
cell.setCellStyle(style);
cell.setCellValue("Categories");
cell = row.createCell(c++);
cell.setCellStyle(style);
cell.setCellValue("Tags");
//Create data cell
for(Employee employee:employees){
row = sheet.createRow(r++);
c = 0;
row.createCell(c++).setCellValue(employee.getName());
row.createCell(c++).setCellValue(employee.getDepartment());
row.createCell(c++).setCellValue(employee.getP_grade());
// row.createCell(c++).setCellValue(article.getTags().toString());
}
for(int i = 0 ; i < 3; i++)
sheet.autoSizeColumn(i, true);
}
}
public class MyController {
@RequestMapping("/viewExcel")
public ModelAndView viewExcel(Map<String, Object> map) {
map.put("viewList", myService.viewExcel());
return new ModelAndView(new ViewExcel(), map);
}
@RequestMapping("/myExcelView")
public ModelAndView myExcelView(Map<String, Object> map) {
map.put("viewList", myService.viewExcel());
return new ModelAndView(new MyExcelView(), map);
}
}