在Struts 2中實現文件下載

download.jsp代碼顯示:

form提交:
按鈕:<input type="button" onclick="toDownLoad('<%=webroot%>/expExamMarksAuditList.action')" value="導出excel">
utl:<%=webroot%>/newalregister/expExamMarksAuditList.action')

function toDownLoad(url){
     form00.action = url;
     form00.submit();
}

 

struts.xml文件代碼

<!-- 下載 導出審批管理 -->
<action name="expExcel" class="com.DownLoadAction" method="expExcel">
	<param name="inputPath">/file/marks.xls</param>
	<param name="fileName">marks.xls</param>
	
	<result name="success" type="stream">
		<!-- 下載文件的類型,可以去 tomcat\conf\web.xml下找 --> 
		<param name="contentType">  
            application/vnd.ms-excel  
        </param>  
        <!--  返回流 excelStream爲action中的流變量名稱 -->
        <param name="inputName">excelStream</param>  
        <!-- attachment 這個位置的參數挺特殊的,可以設置成下載時,是否出現個下載提示框,或者直接下載之類的,  
        fileName指定生成的文件名字 爲action中變量  -->
		<param name="contentDisposition">
			attachment;filename="${excelFileName}"
		</param>
		<!-- 緩存大小 -->
		<param name="bufferSize">4096</param>
	</result>
</action>

整個配置文件中最重要的兩個變量就是 excelStream、excelFileName,這兩個變量一定要在action中有定義,否則會報錯。

變量templatePosition,這個是運用模板的路徑,用模板的意思,是可以預先設置好各種單元格包括顏色,對齊方式,數據格式,

這些東西在程序裏也可以控制,但太累,還是用模板吧,代碼量少,假如客戶想換個顏色什麼的也簡單,改下模板就好。

DownLoadAction.java

package com;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class DownLoadAction extends ActionSupport {

	private InputStream excelStream; // 輸出流變量

	private String excelFileName; // 下載文件名

	private String templatePosition; // 模板路徑

	private DownloadService downloadService;

	public void setDownloadService(DownloadService downloadService) {
		this.downloadService = downloadService;
	}

	public DownloadService getDownloadService() {
		return downloadService;
	}

	public String expExcel() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Map<String, Object> aa = Map<String, Object> aa = downloadService
    				.expExcel(contextPath + "WEB-INF/classes"
      				+ templatePosition);
		this.excelStream = (InputStream) aa.get("stream");
		this.excelFileName = (String) aa.get("excelName") + ".xls";
		return SUCCESS;
	}

	/**
	 * 提供中文轉換的功能
	 * 
	 * @return
	 */
	public String getExcelFileName() {
		try {
			return new String(this.excelFileName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "aaa.xls";
	}

	// 對應struts.xml文件中的inputName參數 <param name="inputName">excelStream</param>
	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getTemplatePosition() {
		return templatePosition;
	}

	public void setTemplatePosition(String templatePosition) {
		this.templatePosition = templatePosition;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}
}

DownloadService.java

public Map<String,Object> expExcel(String templatePosition) {  
        Map<String,Object> returnMap=new HashMap<String, Object>();  
        InputStream is;  
        ByteArrayInputStream aas;  
        try {  
            is = new FileInputStream(templatePosition);  
            HSSFWorkbook wb = new HSSFWorkbook(is);  
            HSSFSheet sheet = wb.getSheetAt(0);  
              
            /**
			 * .... 構建 sheet 代碼
			 */  
          
            ByteArrayOutputStream os = new ByteArrayOutputStream();  
            try {  
                wb.write(os);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            byte[] content = os.toByteArray();  
            aas = new ByteArrayInputStream(content);  
            returnMap.put("stream", aas);  
            returnMap.put("excelName", titlePreStr);  
              
            return returnMap;  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
	return null;  
}  

service中返回的是個 Map,當中包括返回流跟 excel 名稱兩部分,因爲我們的需求 excel 的標題就是文件名,所有這樣寫,挺好的,另外再附上一個我自己寫的解析樣式的方法,個人覺得挺好用

/**
 * 樣式讀取方法
 * 
 * @param styleName
 *            樣式名數組
 * @param styleRow
 *            樣式行
 * @param startCol
 *            開始列位置
 * @param startCol
 *            空白樣式列位置 null:不進行空替換
 * @return
 */  
public static Map<String, HSSFCellStyle> readStyle(String[] styleName,  
        HSSFRow styleRow, short startCol, Integer blankCol) {  
    Map<String, HSSFCellStyle> returnMap = new HashMap<String, HSSFCellStyle>();  
    HSSFCellStyle blankStyle = null;  
    if (null != blankCol) {  
        blankStyle = styleRow.getCell(blankCol.shortValue()).getCellStyle();  
        styleRow.getCell(blankCol.shortValue()).setCellValue("");  
        }  
  
        for (String name : styleName) {  
            HSSFCell cell = styleRow.getCell(startCol);  
            HSSFCellStyle style = cell.getCellStyle();  
            returnMap.put(name, style);  
            cell.setCellValue("");  
        if (null != blankStyle) {  
            cell.setCellStyle(blankStyle);  
        }  
        startCol++;  
    }  
    return returnMap;  
}  

把樣式都放到一個Map裏,方法間傳遞樣式的時候只需要傳這個樣式Map就好,避免傳一堆樣式參數



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