java導出導入excel,對jxl的封裝

JExcelOperator.java
導出導入的類


public class JExcelOperator {
	/*定義默認的列寬*/
	private static final int DEFAULT_COLUMN_WIDTH = 10;
	/*定義默認的工作薄名稱*/
	private static final String DEFAULT_WORK_TITLE = "教育";	
	/*定義默認的工作表標題樣式*/
	private static final ITitleFormat DEFAULT_TITLE_FORMAT = new DefaultTitleFormat();
	/*定義默認的工作表表頭樣式*/
	private static final IColumnFormat DEFAULT_COLUMN_FORMAT = new DefaultColumnFormat();
	/*定義默認的工作表數據樣式*/
	private static final IDataCellFormat DEFAULT_DATACELL_FORMAT = new DefaultDataCellFormat();
	
    /*指定工作表標題的 樣式*/
	private ITitleFormat titleFormat ;    
    /*指定表頭樣式*/
	private IColumnFormat columnFormat ;
    /*指定數據行 樣式*/
	private IDataCellFormat dataFormat ;

	/**
	 * 導出Excel .成功導出,返回true;否則返回false
	 * @param request 
	 * HTTP請求對象
	 * @param response 
	 * HTTP響應對象
	 * @param workTitle 
	 * 工作薄名稱
	 * @param title
	 * 工作表標題
	 * @param columns
	 * 列名數組
	 * @param widths
	 * 列寬度數組
	 * @param dataList
	 * 要導出的對象集合
	 * @param objectMapper
	 * 對象解析器,將一個對象解析成一行數據
	 */
	@SuppressWarnings("unchecked")
	public boolean exportExcel(HttpServletRequest request, HttpServletResponse response, String workTitle,String title,
			String[] columns, int[] widths,List dataList, IObjectMapper objectMapper) {
		OutputStream out = null;
		WritableWorkbook wbook = null;
		try {
			//斷言 objectMapper  不能爲空
			Assert.notNull(objectMapper, "對象解析器不能爲空");
			if(workTitle == null || workTitle.trim().equals("")){
				workTitle = DEFAULT_WORK_TITLE;
			}
			out = response.getOutputStream();
			response.setContentType("application/msexcel");// 定義輸出類型
			String fileName = workTitle;
			//獲取瀏覽器類型
			String user_agent = request.getHeader("User-Agent").toLowerCase();
			//爲不同的瀏覽器,對文件名進行不同的編碼轉換
			if(user_agent.indexOf("firefox") > 0){
				 fileName =  new String(workTitle.getBytes("UTF-8"), "iso8859-1");
			}else{
				fileName = URLEncoder.encode(workTitle, "UTF-8");
			}
			
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName + ".xls");         // 設定輸出文件頭

			wbook = Workbook.createWorkbook(out); // 建立excel文件
			WritableSheet wsheet;
			if(workTitle != null && !workTitle.equals("")){
				 wsheet = wbook.createSheet(workTitle, 0); // 創建一個工作薄
			}else{
				 wsheet = wbook.createSheet("", 0);       
			}
			
			int headerIndex = 0;  //記錄表頭所在的行
			
			if(title != null && !title.equals("")){
				headerIndex = 1;
				// 設置excel標題
				wsheet.addCell(new Label(0, 0, title, this.getTitleFormat().getTitleCellFormat()));
			}

			// 在一新行中, 爲表格添加表頭
			if(columns != null){
				for (int i = 0; i < columns.length; i++) {
					if(widths != null && widths.length > 0){
						if((i + 1) <= widths.length ){
							wsheet.setColumnView(i, widths[i]);
						}else{
							wsheet.setColumnView(i, DEFAULT_COLUMN_WIDTH);
						}
					}else{
						wsheet.setColumnView(i, DEFAULT_COLUMN_WIDTH);
					}
					wsheet.addCell(new Label(i, headerIndex, columns[i],this.getColumnFormat().getTitleCellFormat()));
				}
			}

			//將集合中的數據添加到excel的工作表中
			if(dataList != null){
				for (int i = 0; i < dataList.size(); i++) {  
					Object obj = dataList.get(i);
					objectMapper.toExcelRow(wsheet,this.dataFormat, i + headerIndex + 1, obj);
				}
			}

			// 主體內容生成結束
			wbook.write(); // 寫入文件
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		} finally {
			if (wbook != null) {
				try {
					wbook.close();
				} catch (WriteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 導入Excel,將Excel 中的數據導入到List 中 
	 * @param input
	 * 指定輸入流 
	 * @param index
	 * 工作博的序號 (從0開始)
	 * @param startIndex
	 * 指定從第幾行開始讀入 (第一行對應的index爲0) 
	 * @param rowMapper
	 * 行包裝器(負責將一行數據轉變成一個數據對象)
	 */
	@SuppressWarnings("unchecked")
	public List getDataFromExcel(InputStream input, int index, int startIndex,
			IRowMapper rowMapper) {
		// TODO Auto-generated method stub
		Workbook rwb = null;
		try {
			List list = new ArrayList();
			 rwb = Workbook.getWorkbook(input);
			 Assert.isTrue(index < rwb.getSheets().length && index >= 0, "爲index指定的值  " + index + " 無效 ");
			 
			Sheet st = rwb.getSheet(index);
			startIndex = (startIndex < 0)?0:startIndex;
			Assert.isTrue(startIndex < st.getRows(), "爲startIndex指定的值   " + startIndex + " 無效");
			Assert.notNull(rowMapper, "行包裝器沒有指定");
				for (int i = startIndex; i < st.getRows(); i++) {
					Object obj = rowMapper.toObject(st, i);
					if(obj != null){
						list.add(obj);
					}
				}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			if(rwb != null){
				rwb.close();
			}
		}
	}

	/**
	 * 導入Excel,將Excel中的數據導入到List 中 
	 * @param input
	 * 指定輸入流 
	 * @param title
	 * 工作博的名稱
	 * @param startIndex
	 * 指定從第幾行開始讀入(第一行對應的index爲0)
	 * @param rowMapper
	 * 行包裝器(負責將一行數據轉變成一個數據對象)
	 */
	@SuppressWarnings("unchecked")
	public List getDataFromExcel(InputStream input, String title, int startIndex,
			IRowMapper rowMapper) {
		Workbook rwb = null;
		try {
			List list = new ArrayList();
			 rwb = Workbook.getWorkbook(input);
			Assert.notNull(title,"title參數不能爲空");
			Sheet st = rwb.getSheet(title);
			Assert.notNull(st,"爲title參數指定的值:" + title + "無效");
			startIndex = (startIndex < 0)?0:startIndex;
			Assert.isTrue(startIndex < st.getRows(), "爲startIndex指定的值   " + startIndex + " 無效");
			Assert.notNull(rowMapper, "行包裝器沒有指定");
				for (int i = startIndex; i < st.getRows(); i++) {
					Object obj = rowMapper.toObject(st, i);
					if(obj != null){
						list.add(obj);
					}
				}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			if(rwb != null){
				rwb.close();
			}
		}
		
	}

	@SuppressWarnings("unchecked")	
	public void setTitleFormat(ITitleFormat titleFormat) {
		this.titleFormat = titleFormat;
	}
	@SuppressWarnings("unchecked")
	public void setColumnFormat(IColumnFormat columnFormat) {
		this.columnFormat = columnFormat;
	}
	@SuppressWarnings("unchecked")
	public void setDataFormat(IDataCellFormat dataFormat) {
		this.dataFormat = dataFormat;
	}
	@SuppressWarnings("unchecked")
	public ITitleFormat getTitleFormat() {
		//如果沒有設置工作表標題樣式,就給它一個默認樣式
		if(this.titleFormat == null || this.titleFormat.getTitleCellFormat() == null){
			this.titleFormat = DEFAULT_TITLE_FORMAT;
		}
		return titleFormat;
	}
	@SuppressWarnings("unchecked")
	public IColumnFormat getColumnFormat() {	
		//如果沒有設置工作表標題樣式,就給它一個默認樣式
		if(this.columnFormat == null || this.columnFormat.getTitleCellFormat() == null){
			this.columnFormat = DEFAULT_COLUMN_FORMAT;
		}
		return columnFormat;
	}
	@SuppressWarnings("unchecked")
	public IDataCellFormat getDataFormat() {
		if(this.dataFormat == null){
			this.dataFormat = DEFAULT_DATACELL_FORMAT;
		}
		return dataFormat;
	}

}



/*
 * 該類負責將一個對象轉變成Excel 中的一行數據
 */
public interface IObjectMapper {
	/*
	 * 將obj 對象 轉變成sheet工作表 中的第 rowNum行數據
	 * sheet  操作的工作表
	 * dataFormat 指定數據行 樣式
	 * rowNum 表示 行號
	 * obj    要轉換的對象
	 */
    public void toExcelRow(WritableSheet sheet,IDataCellFormat dataFormat, int rowNum,Object obj)  throws RowsExceededException, WriteException;
    
}



/*
 * Excel 行包裝器, 負責將excel 中一行數據轉變成一個對象
 */
public interface IRowMapper {

	/*
	 * 定義如何將一個excel 中的一行 轉變成一個對象,返回裝有excel數據的對象
	 * sheet  操作的工作表
	 * rowNum 表示 行號
	 */
    public Object toObject(Sheet sheet,int rowNum)  throws RowsExceededException, WriteException;
}





接下來是定義默認樣式的類

//描述工作博單元格樣式的根接口
public interface ICellFormat {
	public WritableCellFormat getTitleCellFormat();
}


//該接口爲 標識接口,所有描述工作博標題樣式的類都要實現此接口
public interface ITitleFormat extends ICellFormat{
	public WritableCellFormat getTitleCellFormat();
}


//該接口爲 標識接口,所有描述工作博列名樣式的類都要實現此接口
public interface IColumnFormat extends ICellFormat{

}


/*
 * 該接口定義瞭如何爲不同的數據類型指定不同的樣式的方法
 */
public interface IDataCellFormat {
	public WritableCellFormat getDataCellFormat(CellType type);
}


/*
 * 定義一個工作博標題樣式的默認實現
 */
@Component
public class DefaultTitleFormat implements ITitleFormat{

	public WritableCellFormat getTitleCellFormat() {
		// TODO Auto-generated method stub
	    WritableCellFormat wcf = null;   
	       try {   
	           //字體樣式   
	           WritableFont wf = new WritableFont(WritableFont.TIMES,20, WritableFont.BOLD,true);//最後一個爲是否italic   
	           wf.setColour(Colour.RED);   
	           wcf = new WritableCellFormat(wf);   
	           //對齊方式   
	           wcf.setAlignment(Alignment.CENTRE);   
	           wcf.setVerticalAlignment(VerticalAlignment.CENTRE);   
	           //邊框   
	           wcf.setBorder(Border.ALL,BorderLineStyle.THIN);   
	              
	           //背景色   
	           wcf.setBackground(Colour.GREY_25_PERCENT);   
	       } catch (WriteException e) {   
	        e.printStackTrace();   
	       }   
	       return wcf;    
	}

}


/*
 * 定義一個工作博表頭樣式的默認實現
 */
@Component
public class DefaultColumnFormat  implements IColumnFormat{

	@Override
	public WritableCellFormat getTitleCellFormat() {
	    WritableCellFormat wcf = null;   
	       try {   
	           //字體樣式   
	           WritableFont wf = new WritableFont(WritableFont.TIMES,15, WritableFont.NO_BOLD,false);//最後一個爲是否italic   
	           wf.setColour(Colour.BLUE);   
	           wcf = new WritableCellFormat(wf);   
	           //對齊方式   
	           wcf.setAlignment(Alignment.CENTRE);   
	           wcf.setVerticalAlignment(VerticalAlignment.CENTRE);   
	           //邊框   
	           wcf.setBorder(Border.ALL,BorderLineStyle.THIN);   
	              
	           //背景色   
	           wcf.setBackground(Colour.GREY_25_PERCENT);   
	       } catch (WriteException e) {   
	        e.printStackTrace();   
	       }   
	       return wcf;    
	}

}


/*
 * 定義一個工作博數據行樣式的默認實現
 */
@Component
public class DefaultDataCellFormat implements IDataCellFormat{

	@Override
	public WritableCellFormat getDataCellFormat(CellType type) {
		// TODO Auto-generated method stub
		  WritableCellFormat wcf = null;   
	       try {   
	           //字體樣式   
	           if(type == CellType.NUMBER || type == CellType.NUMBER_FORMULA){//數字   
	              NumberFormat nf = new NumberFormat("#.00");   
	              wcf = new WritableCellFormat(nf);    
	           }else if(type == CellType.DATE || type == CellType.DATE_FORMULA){//日期   
	               jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd hh:mm");    
	               wcf = new jxl.write.WritableCellFormat(df);    
	           }else{   
	               WritableFont wf = new WritableFont(WritableFont.TIMES,10, WritableFont.NO_BOLD,false);//最後一個爲是否italic   
	               wcf = new WritableCellFormat(wf);   
	           }   
	           //對齊方式   
	           wcf.setAlignment(Alignment.CENTRE);   
	           wcf.setVerticalAlignment(VerticalAlignment.CENTRE);   
	           //邊框   
	           wcf.setBorder(Border.LEFT,BorderLineStyle.THIN);   
	           wcf.setBorder(Border.BOTTOM,BorderLineStyle.THIN);   
	           wcf.setBorder(Border.RIGHT,BorderLineStyle.THIN);   
	           //背景色   
	           wcf.setBackground(Colour.WHITE);   
	              
	           wcf.setWrap(true);//自動換行   
	              
	       } catch (WriteException e) {   
	        e.printStackTrace();   
	       }   
	       return wcf;    
	}

}

用到第三方jar包:

spring3,jxl.jar



在spring mvc action裏面如何使用?

@Controller
@RequestMapping(value = "/example/excel")
public class ExcelExampleAction {
	private IBaseService<SysStudycentre> sysStudycentreService; // 定義學習中心服務引用
	private JExcelOperator excelOperator;   

	// 注入名爲sysStudycentreService 的IBaseService<SysStudycentre> 對象
	@Resource(name = "sysStudycentreService")
	public void setSysStudycentreService(IBaseService<SysStudycentre> sysStudycentreService) {

		this.sysStudycentreService = sysStudycentreService;
	}

	// 注入名爲 excelOperator 的JExcelOperator 對象
	@Resource(name = "excelOperator")
	public void setExcelOperator(JExcelOperator excelOperator) {
		this.excelOperator = excelOperator;
	}	
	
	// 導出excel
	@RequestMapping(value = "getexcel")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public void exportToExcel(Model model,HttpServletRequest request,HttpServletResponse response) {
		List<SysStudycentre> sysStudyCenters = this.sysStudycentreService.findAll();
		   //導出到excel,並將導出文件發往客戶端
			excelOperator.exportExcel(request,response, "學習中心",null, new String[]{"名稱","聯繫人","聯繫方式","更新時間"},new int[]{10,20,30,30}, sysStudyCenters, new IObjectMapper(){
				@Override
				public void toExcelRow(WritableSheet sheet,
						IDataCellFormat dataFormat, int rowNum, Object obj)
						throws RowsExceededException, WriteException {
					// TODO Auto-generated method stub
					if(dataFormat != null){
						    //dataFormat.getDataCellFormat(CellType.STRING_FORMULA)    指定單元格 數據使用的格式
						    sheet.addCell(new Label(0,  rowNum, ((SysStudycentre)obj).getFname(),dataFormat.getDataCellFormat(CellType.STRING_FORMULA))); // 學習中心名稱
						    sheet.addCell(new Label(1, rowNum,((SysStudycentre)obj).getFcontactor(),dataFormat.getDataCellFormat(CellType.STRING_FORMULA) )); // 聯繫人
						    sheet.addCell(new Label(2, rowNum,((SysStudycentre)obj).getFmobilephone(),dataFormat.getDataCellFormat(CellType.NUMBER_FORMULA) )); // 聯繫方式
						    sheet.addCell(new Label(3, rowNum,((SysStudycentre)obj).getFupdatetime().toString(),dataFormat.getDataCellFormat(CellType.DATE_FORMULA) )); // 更新時間
					}else{
					    sheet.addCell(new Label(0,  rowNum, ((SysStudycentre)obj).getFname())); // 學習中心名稱
					    sheet.addCell(new Label(1, rowNum,((SysStudycentre)obj).getFcontactor() )); // 聯繫人
					    sheet.addCell(new Label(2, rowNum,((SysStudycentre)obj).getFmobilephone() )); // 聯繫方式
					    sheet.addCell(new Label(3, rowNum,((SysStudycentre)obj).getFupdatetime().toString() )); // 更新時間
					}
				}
			});
	}
	
	
	// 從excel 中導入數據
	@RequestMapping(value = "exportToList")
	@SuppressWarnings("unchecked")
	public String exportToList(Model model,HttpServletRequest request,HttpServletResponse response) {
		String filePath = "";
		try{
			//取得文件路徑
			 filePath = request.getSession().getServletContext().getRealPath("") + "\\WEB-INF\\classes\\data\\studyCenter2.xls";
			FileInputStream in = new FileInputStream(filePath);
			List list = new JExcelOperator().getDataFromExcel(in, 0, 3, new IRowMapper(){
				@Override
				public Object toObject(Sheet sheet, int rowNum)
						throws RowsExceededException, WriteException {
					// TODO Auto-generated method stub
					SysStudycentre studyCentre = new SysStudycentre();
					studyCentre.setFname(sheet.getCell(0, rowNum).getContents());
					studyCentre.setFcontactor(sheet.getCell(1, rowNum).getContents());
					studyCentre.setFmobilephone(sheet.getCell(2, rowNum).getContents());
					return studyCentre;
				}
				
			});
			for(Object obj:list){
				System.out.println(((SysStudycentre)obj).getFname());
			}
			//將集合存入model 中
			model.addAttribute("studyCenterList",list);
			return "example/exceldata";
		} catch (FileNotFoundException e) {
			request.setAttribute("message",  filePath + "文件沒找到");
			return "example/error";
		}
	}
	
}



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