1. 程式人生 > >JAVA下載功能的實現

JAVA下載功能的實現

1、將資料下載儲存在excel表格中,程式碼如下:

package zh.pujin.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import zh.pujin.entity.Registeruser;

public class ExcelExport {

	public String excelExport(List<Registeruser> registerUserByCondition ,HttpServletResponse resp){
		int result = 0;
		String[] title = {"序號","手機號","城市"};                  //根據需要設定
		try {
			resp.setContentType("application/binary;charset=UTF-8");
			ServletOutputStream out = resp.getOutputStream();
			String name = "檔案" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
			String fileName = new String(name.getBytes("GB2312"), "ISO_8859_1");
			resp.setHeader("Content-disposition", "attachment;filename="+fileName+".xls");
			try{
				HSSFWorkbook hwb = new HSSFWorkbook();             // 建立webBook,對應一個excel檔案
				HSSFSheet sheet = hwb.createSheet("資料測試");        // 新增一個sheet
				HSSFRow row = sheet.createRow(0);                  // 標題欄
				HSSFCellStyle style = hwb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				HSSFCell cell = null;
				for(int i=0; i<title.length; i++){                         //標題的內容
					cell = row.createCell(i);
					cell.setCellValue(title[i]);
					cell.setCellStyle(style);
					}
				if(registerUserByCondition.size() > 0){
					for(int i=0; i<registerUserByCondition.size(); i++){     //獲取的資料
						row = sheet.createRow(i+1);
						row.createCell(0).setCellValue(String.valueOf(registerUserByCondition.get(i).getId()).trim());
						row.createCell(1).setCellValue(String.valueOf(registerUserByCondition.get(i).getUserphone()).trim());
						row.createCell(2).setCellValue(String.valueOf(registerUserByCondition.get(i).getCity()).trim());
					}
				}
				try{
					hwb.write(out);
					out.flush();
					out.close();
				} catch(Exception e) {
					e.getMessage();
					result = 1;
					return null;
				}
			} catch(Exception e){
				e.getMessage();
				result = 1;
				return null;
			}
		} catch (IOException e) {
			e.getMessage();
			result = 1;
			return null;
		}
		return null;
	}
	
	
}