天天看點

ssh+jxl将表格導出為Excel

       首先準備jxl.jar.

      然後讓我們了解了解這個jxl,Excel本來就有工作簿、工作表、單元格等屬性,是以我們從資料庫導出表格也必須先有工作簿(workbook)、工作表(sheet)、單元格(label)。實作導出表格也是從三個入手。

     首先建立一個writeworkbook對象

           Writableworkbook  book=Workbook.createWorkbook(new File(path));

     然後建立工作表sheet對象

            WritableSheet sheet=book.createSheet("第一頁",0);

     建立單元格Label

           Label label1=new Label(0,0"XXX");       

     最後sheet添加單元格

          sheet.addCell(label1);

          book.write();

          book.close();

      下面是我的例子。

public String exportExcel(){
		String path=ServletActionContext.getServletContext().getRealPath("images/user");
		List userList=userService.findAll();
		try{
			// 打開檔案
			WritableWorkbook book = Workbook.createWorkbook(new File(path,"apply_users.xls"));
			// 定義格式, 字型, 下劃線, 斜體, 粗體, 顔色 
			WritableFont wf = new WritableFont(WritableFont.ARIAL, 10, 
			    WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, 
			jxl.format.Colour.BLACK); 
			// 建立格式化對象執行個體    
			WritableCellFormat totalx2Format = new WritableCellFormat(wf);    
			// 垂直居中    
			totalx2Format.setVerticalAlignment(VerticalAlignment.CENTRE);    
			//自動換行
			totalx2Format.setWrap(true);
			// 水準居中    
			totalx2Format.setAlignment(Alignment.CENTRE); 
			// 生成名為“第一頁”的工作表,參數0表示這是第一頁
			WritableSheet sheet = book.createSheet(" 第一頁 ", 0);
			// 在Label對象的構造子中指名單元格位置是第一列第一行(0,0)
			Label label1 = new Label(0, 0, " 序号 ",totalx2Format);
			Label label2 = new Label(1, 0, " 姓名 ",totalx2Format);
			Label label3 = new Label(2, 0, " 學院 ",totalx2Format);
			Label label4 = new Label(3, 0, " 專業 ",totalx2Format);
			Label label5 = new Label(4, 0, " 班級 ",totalx2Format);
			Label label6 = new Label(5, 0, " 一卡通号 ",totalx2Format);
			Label label7 = new Label(6, 0, " 聯系電話 ",totalx2Format);
			//給sheet電子版中所有的列設定預設的列的寬度;  
			 sheet.getSettings().setDefaultColumnWidth(30);  
			// 将定義好的單元格添加到工作表中
			sheet.addCell(label1);
			sheet.addCell(label2);
			sheet.addCell(label3);
			sheet.addCell(label4);
			sheet.addCell(label5);
			sheet.addCell(label6);
			sheet.addCell(label7);
			
			ACMuser user=new ACMuser();
			for (int i = 0; i < userList.size(); i++) {
				user=(ACMuser) userList.get(i);
				sheet.addCell(new Label(0, i+1, i+1+"",totalx2Format));
				sheet.addCell(new Label(1, i+1, user.getUserName(),totalx2Format));
				sheet.addCell(new Label(2, i+1, user.getAcademy(),totalx2Format));
				sheet.addCell(new Label(3, i+1, user.getMajor(),totalx2Format));
				sheet.addCell(new Label(4, i+1, user.getUserClass(),totalx2Format));
				sheet.addCell(new Label(5, i+1, user.getCardnumber(),totalx2Format));
				sheet.addCell(new Label(6, i+1, user.getPhone(),totalx2Format));
				
			}
			book.write();
			book.close();
		}catch(Exception e){
			return "toError";
		}
		return "toExportExcel";
	}