springmvc下载excel大体步骤

来源:互联网 发布:携程移动端日历js插件 编辑:程序博客网 时间:2024/06/07 00:01
package com.tvs.controller;import java.io.IOException;import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Font;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 org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping({"/excel"})public class ExcelController{  @RequestMapping(method={org.springframework.web.bind.annotation.RequestMethod.GET})  public void dewnExcel(HttpServletRequest request, HttpServletResponse response)  {    HSSFWorkbook wb = (HSSFWorkbook)createExcel();    try    {      response.setHeader("Content-Disposition", "attachment; filename=appointmentUser.xls");      response.setContentType("application/vnd.ms-excel; charset=utf-8");      OutputStream out = response.getOutputStream();      wb.write(out);      out.flush();      out.close();    }    catch (IOException e)    {      e.printStackTrace();    }  }    public Workbook createExcel()  {    Workbook wb = new HSSFWorkbook();        Sheet sheet = wb.createSheet("第一页");    for (int i = 0; i < 2; i++) {      sheet.setColumnWidth((short)i, 5355);    }    Row row = sheet.createRow(0);        CellStyle cs = wb.createCellStyle();    CellStyle cs2 = wb.createCellStyle();        Font f = wb.createFont();    Font f2 = wb.createFont();        f.setFontHeightInPoints((short)10);    f.setColor(IndexedColors.BLACK.getIndex());    f.setBoldweight((short)700);        f2.setFontHeightInPoints((short)10);    f2.setColor(IndexedColors.BLACK.getIndex());        cs.setFont(f);    cs.setBorderLeft((short)1);    cs.setBorderRight((short)1);    cs.setBorderTop((short)1);    cs.setBorderBottom((short)1);    cs.setAlignment((short)2);        cs2.setFont(f2);    cs2.setBorderLeft((short)1);    cs2.setBorderRight((short)1);    cs2.setBorderTop((short)1);    cs2.setBorderBottom((short)1);    cs2.setAlignment((short)2);    for (int i = 0; i < 2; i++)    {      Cell cell = row.createCell(i);      cell.setCellValue("张三" + i);      cell.setCellStyle(cs);    }    for (short i = 1; i < 2; i = (short)(i + 1))    {      Row row1 = sheet.createRow(i);      for (short j = 0; j < 2; j = (short)(j + 1))      {        Cell cell = row1.createCell(j);        cell.setCellValue("李四" + j);        cell.setCellStyle(cs2);      }    }    return wb;  }}

原创粉丝点击