Springmvc下載Excel案例(一)

SpringMVC下載Excel報表,這樣一個比較簡單的功能,但是在項目中都會遇到一些這樣那樣的小問題,這裏將工作中遇到的這些問題進行總結吧,希望能幫助初學者。

關於SpringMVC的知識這裏就不多作細說,直接上代碼。

ExcelAction.java 後端Controller類

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.util.ExcelUtil;


@Controller
public class ExcelAction {

	@RequestMapping("/download.do")
	public ResponseEntity download(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		byte[] content = new ExcelUtil().getExcelFileByte();
		
		HttpHeaders headers = new HttpHeaders();
		if(content == null || content.length == 0){
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			return new ResponseEntity(null, headers, HttpStatus.OK);
		}
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment",new String("測試Excel.xls".getBytes("utf-8"),"ISO-8859-1"));
		return new ResponseEntity(content, headers, HttpStatus.CREATED);
	}
}

ExcelUtil.java 生成Excel的類

package com.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;

import com.bean.Student;


public class ExcelUtil {

	public byte[] getExcelFileByte(){
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] content = null;
		
		try {
			// 1.準備數據
			List<Student> list = new ArrayList<Student>();
			list.add(new Student("小明","男","18","籃球"));
			list.add(new Student("小唐","男","19","足球"));
			list.add(new Student("小紅","女","17","畫畫"));
			list.add(new Student("小倩","女","19","看電影"));
			
			// 2.創建excel
			// 聲明一個工作簿
			HSSFWorkbook workbook = new HSSFWorkbook();
			// 生成一個表格
			HSSFSheet sheet = workbook.createSheet("學生信息");
			//產生表格標題行
			HSSFRow row0 = sheet.createRow(0);
			//創建表格
			HSSFCell cellData = row0.createCell(0);
			cellData.setCellStyle(getStatiscsRangeStyle(workbook));
			cellData.setCellValue("學生信息統計信息");
			//創建excel列名
			String[] headers = new String[]{"姓名", "性別", "年齡", "愛好"};
			for(int i=0;i<headers.length;i++){
				sheet.setColumnWidth(i, 4000);
			}
			//合併單元格
			CellRangeAddress cra = new CellRangeAddress(0,0,0,headers.length - 1);
			sheet.addMergedRegion(cra);
			
			HSSFRow row2 = sheet.createRow(1);
			for(int i=0;i<headers.length;i++){
				HSSFCell cell = row2.createCell(i);
				cell.setCellStyle(getHeaderStyle(workbook));
				cell.setCellValue(headers[i]);
			}
			//設置數據區
			setCellValue(list,workbook,sheet);
			workbook.write(bos);
			content = bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return content;
	}
	
	
	/**
     * excel文檔第一行的樣式
     * @param workbook
     * @return
     */
    private HSSFCellStyle getStatiscsRangeStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = getBaseCellStyle(workbook);
        HSSFFont font = workbook.createFont();
        font.setFontName("黑體");
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        return style;
    }
    
    public HSSFCellStyle getBaseCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        return style;
    }
    
    /**
     * 頭數據格式
     * @param workbook
     * @return
     */
    private HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = getBaseCellStyle(workbook);
        HSSFFont font = workbook.createFont();
        font.setFontName("黑體");
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        return style;
    }
    
    /**
     * excel寫入數據
     * @param list
     * @param workbook
     * @param sheet
     */
    private void setCellValue(List<Student> list,HSSFWorkbook workbook, HSSFSheet sheet){
    	HSSFCellStyle cellStyle = getBaseCellStyle(workbook);
    	int index = 2;
    	for(Student stu : list){
    		HSSFRow row = sheet.createRow(index);
    		HSSFCell cell0 = row.createCell(0);
    		cell0.setCellStyle(cellStyle);
    		cell0.setCellValue(stu.getName());
    		HSSFCell cell1 = row.createCell(1);
    		cell1.setCellStyle(cellStyle);
    		cell1.setCellValue(stu.getSex());
    		HSSFCell cell2 = row.createCell(2);
    		cell2.setCellStyle(cellStyle);
    		cell2.setCellValue(stu.getAge());
    		HSSFCell cell3 = row.createCell(3);
    		cell3.setCellStyle(cellStyle);
    		cell3.setCellValue(stu.getLove());
    		index++;
    	}
    }
}

Student.java  實體bean

package com.bean;

public class Student {

	private String name;
	
	private String sex;
	
	private String age;
	
	private String love;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getLove() {
		return love;
	}

	public void setLove(String love) {
		this.love = love;
	}
	
	public Student(String name, String sex, String age, String love) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.love = love;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", age=" + age + ", love=" + love + "]";
	}
}


前端調用代碼

<!DOCTYPE html>
<html>
	<head>
		<title>我的測試</title>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	</head>
	
	<body>
		<a id="download1">下載excel文檔</a>
		<br>
		<a id="download2">下載Excel文檔2</a>
	</body>
	<script type="text/javascript" src="../js/jquery.min.js"></script>
	<script type="text/javascript">
		$("#download1").click(function(){
			var contextHref = getContextPath();
			window.location.href = contextHref+"/download.do";
		});
		
		function getContextPath(){     
 		    var pathName = document.location.pathname;     
		    var index = pathName.substr(1).indexOf("/");     
		    var contextRoot = pathName.substr(0,index+1);
		    var port = window.location.port;
		    return "http://localhost:"+port+contextRoot;
		} 
	</script>
</html>

這裏前端調用用的是window.location.href 的方式,本機測試通過






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章