頭像上傳與使用POI導入導出文件列表

一、頭像上傳

JSP頁面

<span style="font-size:18px;">private File headImage;
private String headImageFileName;//文件上傳時,這兩個變量的命名格式是固定的,都是 文件+FileName
private String headImageContentType;//文件+ContentType,隨便改的話就會報錯找不到 sourceEntities,實體源 </span>
注意:還要提供get和set方法
	<span style="font-size:18px;">//添加到數據庫
	public String add(){
		
		try {
			if(user!=null){
				//處理頭像
				if(headImage!=null){
						//1.保存頭像到upload/user
						//獲取保存路徑的絕對地址
						String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");
						//重新給其一個名字
						String fileName=UUID.randomUUID().toString().replaceAll("-", "")
								+headImageFileName.substring(headImageFileName.lastIndexOf("."));//從點最後一次出現的位置截取,即後綴名
						//複製文件
						FileUtils.copyFile(headImage, new File(filePath,fileName));
						//2.設置用戶頭像路徑
						user.setHeadImage("user/"+fileName);
					
				}
				//保存用戶及其對應的角色
				userService.saveUserAndRole(user,userRoleIds);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
		return "list";
	}</span>
在更新用戶的方法中,也需要重寫上傳頭像的方法,因爲用戶是可能更換頭像的。

<span style="color:#000000;">//修改
	public String edit(){
		try {
			if(user!=null){
				//處理頭像
				if(headImage!=null){//如果修改了頭像,就執行
					//1.保存頭像到upload/user
					//獲取保存路徑的絕對地址
					String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");
					//重新給其一個名字
					String fileName=UUID.randomUUID().toString().replaceAll("-", "")
							+headImageFileName.substring(headImageFileName.lastIndexOf("."));
					//複製文件
					FileUtils.copyFile(headImage, new File(filePath,fileName));
					//2.設置用戶頭像路徑
					user.setHeadImage("user/"+fileName);
				
				}
				userService.updateUserAndRole(user,userRoleIds);
			}</span>
數據庫中存儲的不過是圖片的路徑罷了。

當然Struts2的上傳文件支持的jar包也是不可少的。

二、使用POI導入導出文件列表

差點忘了準備工作,導入相關jar包:

下載完後,打開“poi-bin-3.10.1-20140818”獲取操作excel需要的jar包,並將這些jar包複製到項目中。對於只操作2003 及以前版本的excel,只需要poi-3.10.1-20140818.jar,如果需要同時對2007及以後版本進行操作則需要複製

poi-ooxml-3.10.1-20140818.jar,

poi-ooxml-schemas-3.10.1-20140818.jar,以及複製在ooxml-lib目錄下的xmlbeans-2.6.0.jar,dom4j-1.6.1.jar。


1.導出用戶列表爲Excel格式的文件,03版本後綴名是xls,07版本以後xlsx


//導出用戶列表,action層
	public void exportExcel(){
		try {
			//獲取用戶列表
			HttpServletResponse response = ServletActionContext.getResponse();
			//設置內容的類型
			response.setContentType("application/x-excel");
			//告訴瀏覽器是附件以及附件的名字,設置請求頭
			response.setHeader("Content-Disposition",
					"acttachment;filename="
							+new String("用戶列表.xls".getBytes(),"ISO-8859-1"));//防止中文亂碼,固定爲xls03版本,是爲了適用所有用戶
			//獲取輸出流
			ServletOutputStream outputStream = response.getOutputStream();
			userService.exportExcel(userService.findObjects(),outputStream);
			//要先判斷不爲空時再關,否則會報空指針異常
			if(outputStream!=null){
				outputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
2.導入Excel格式的文件並自動生成用戶列表,本質是添加到數據庫在表現層遍歷。

//導入Excel文件
	public String importExcel(){
		//1獲取Excel文件
		if(userExcel!=null){
			//判斷是否是excel
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
				//導入
				userService.importExcel(userExcel,userExcelFileName);
			}
		}
		
		return "list";
	}

public void exportExcel(List<User> userList, ServletOutputStream outputStream) {
		
		ExcelUtils.exportUserExcel(userList, outputStream);
	}

	@Override
	public void importExcel(File userExcel, String userExcelFileName) {
		try {
			FileInputStream fis=new FileInputStream(userExcel);
			//通過判斷,決定讀取那種工作薄
			boolean is03Excel=userExcelFileName.matches("^.+\\.(?i)(xls)$");//  \\轉義點    ?i 表示  忽略大小寫    
			Workbook workbook=is03Excel? new HSSFWorkbook(fis):new XSSFWorkbook(fis) ;
			//讀取表
			Sheet sheet = workbook.getSheetAt(0);//讀取第一個表
			//讀取行,表的有效行數
			if(sheet.getPhysicalNumberOfRows()>2){
				User user=null;
				for(int i=2;i<sheet.getPhysicalNumberOfRows();i++){
					//讀取單元格
					Row row = sheet.getRow(i);
					user=new User();
					//用戶名
				String	name=row.getCell(0).getStringCellValue();
				user.setName(name);
					//賬號
				String account =row.getCell(1).getStringCellValue();
				user.setAccount(account);
					//所屬部門
				String dept=row.getCell(2).getStringCellValue();
				user.setDept(dept);
					//性別
				Cell cell3=	row.getCell(3);
				user.setGender(cell3.getStringCellValue().equals("男"));// equals()方法 返回值爲boolean ,剛好 男  對應着  true ,女  false
					//手機號碼
				String phone="";
				Cell cell4 = row.getCell(4);
				try {
					phone=cell4.getStringCellValue();
				} catch (Exception e) {
					double dphone=cell4.getNumericCellValue();
					phone=BigDecimal.valueOf(dphone).toString();
				}
				user.setPhone(phone);
					//電子郵箱
				String email=row.getCell(5).getStringCellValue();
				user.setEmail(email);
						//生日
					if(row.getCell(6).getDateCellValue()!=null){
						user.setBirthday(row.getCell(6).getDateCellValue());
					}
					//設置默認密碼為123456
					user.setPassword("123456");
					//默認用戶狀態爲 有效
					user.setState(User.USER_STATE_VALID);
					//保存用戶,到數據庫
					userDao.save(user);
				}
			}
			//關閉資源  和輸入流
			workbook.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


核心方法是自建的工具類ExcelUtils.java,再在service層引用其方法即完成導出用戶列表。

 

package cn.sp.core.util;

import java.util.List;

import javax.servlet.ServletOutputStream;

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.util.CellRangeAddress;

import cn.sp.nsfw.user.bean.User;
/**
 * Excel工具類
 * @author 石鵬大神
 *
 */
public class ExcelUtils {
	/**
	 * 導出用戶列表到指定的Excel文件
	 * @param userList 數據庫中查出的用戶列表信息
	 * @param outputStream  向遊覽器輸出的輸出流
	 */
	public  static void exportUserExcel(List<User> userList, ServletOutputStream outputStream) {
		
		try {
			//1.創建工作薄
			HSSFWorkbook workbook=new HSSFWorkbook();
			//1.1創建合併單元格對象
			CellRangeAddress cellRangeAddress=new CellRangeAddress(0,0,0,4);//其實行,最終行,起始列,最終列
			//1.2頭標題樣式
			HSSFCellStyle style1 = createCellStyle(workbook,(short)16);//這裏的數字是 字體大小
			//1.3、列標題樣式
			HSSFCellStyle style2 = createCellStyle(workbook,(short)13);
			//2.創建工作表
			HSSFSheet sheet = workbook.createSheet("用戶列表");//傳入一個工作表名
			//2.1、加載合併單元格對象
			sheet.addMergedRegion(cellRangeAddress);
			//設置默認列寬
			sheet.setDefaultColumnWidth(25);
			//3.創建行
			//3.1、創建頭標題行;並且設置頭標題
			HSSFRow row1 = sheet.createRow(0);
			HSSFCell cell1 = row1.createCell(0);//合併後的單元格爲一個整體,看作爲一個單元格
			//加載單元格樣式並設置值
			cell1.setCellStyle(style1);
			cell1.setCellValue("用戶列表");
			
			//3.2、創建列標題行;並且設置列標題
			HSSFRow row2 = sheet.createRow(1);
			String[] title={"用戶名","賬號","所屬部門","性別","電子郵箱"};
			//依次創建單元格,加載樣式,設置值
			for(int i=0;i<title.length;i++){
				HSSFCell cell = row2.createCell(i);
				
				cell.setCellStyle(style2);
				cell.setCellValue(title[i]);
			}
			
			/**************開始正式內容***************/
			//4、操作單元格;將用戶列表寫入excel
			if(userList!=null){
				for(int j=0;j<userList.size();j++){//每遍歷一次就是一行,一個用戶也對應一行
					HSSFRow rows = sheet.createRow(j+2);
					//用戶名
					HSSFCell cell0 = rows.createCell(0);
					cell0.setCellValue(userList.get(j).getName());
					//賬號
					HSSFCell cell11 = rows.createCell(1);
					cell11.setCellValue(userList.get(j).getAccount());
					//所屬部門
					HSSFCell cell22 = rows.createCell(2);
					cell22.setCellValue(userList.get(j).getDept());
					//性別
					HSSFCell cell33 = rows.createCell(3);
					cell33.setCellValue(userList.get(j).isGender()? "男":"女");
					//電子郵箱
					HSSFCell cell44 = rows.createCell(4);
					cell44.setCellValue(userList.get(j).getEmail());
				}
			}
			
			//5.輸出
			workbook.write(outputStream);
			//關閉資源
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 創建單元格樣式
	 * @param workbook 工作薄
	 * @param fontsize 字體大小
	 * @return
	 */
	private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontsize) {
		//樣式屬於工作薄,由工作薄創建,應用於單元格
		HSSFCellStyle style = workbook.createCellStyle();
		//內容水平居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		//內容垂直居中
		style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
		//創建字體
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗字體
		font.setFontHeightInPoints(fontsize);//設置字體大小,
		//font.setFontHeight(fontsize);    這種只有輸入參數的20分之一大小
		//加載字體
		style.setFont(font);
		return style;
	}
}


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