java實現excel表格上傳和下載
阿新 • • 發佈:2019-01-24
需要匯入excel相應的jar包
form表單需要加上enctype=”multipart/form-data”這個屬性
//封裝上傳檔案物件
private File userExcel;
// 封裝上傳檔案型別的屬性
private String userExcelContentType;
// 封裝上傳檔名的屬性
private String userExcelFileName;
action中所需的欄位
action下載的方法
public String exportExcel() throws IOException{
//1.查詢使用者
List<User> userlist = userService.findObjects();
//2.匯出excel
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/x-execl");
response.setHeader("Content-Disposition", "attachment;filename=" + new String("使用者列表.xls" .getBytes(), "ISO-8859-1"));
ServletOutputStream outputStream = response.getOutputStream();
try {
userService.exportExcel(userlist,outputStream); //封裝的工具類
} catch (Exception e) {
e.printStackTrace();
}
if(outputStream!=null){
outputStream.close();
}
return null;
}
工具類
public class ExcelUtil {
public static void exportExcelUsers(List<User> userlist,ServletOutputStream outputStream) throws Exception{
//1.建立工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 1.1建立合併單元格
CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 6);
// 1.2建立標題樣式
CellStyle style1 = createStyle(workbook, 16);
// 1.3建立列標題樣式
CellStyle style2 = createStyle(workbook, 12);
// 2.建立工作表
Sheet sheet = workbook.createSheet("hello world");
// 設定預設列寬
sheet.setDefaultColumnWidth(15);
// 2.1將合併單元格作用於sheet
sheet.addMergedRegion(cra);
// 3.建立行
Row row = sheet.createRow(0);
// 4.建立單元格
Cell cell = row.createCell(0);
// 5.向單元格寫入資料
cell.setCellValue("使用者列表");
// 6.將單元格加入樣式
cell.setCellStyle(style1);
// 寫列標題
String[] titles = { "使用者名稱", "帳號", "所屬部門", "性別", "手機號碼", "電子郵箱", "生日" };
// 建立列標題行
Row row2 = sheet.createRow(1);
for (int i = 0; i < titles.length; i++) {
// 建立單元格
Cell cell1 = row2.createCell(i);
// 向單元格寫入資料
cell1.setCellValue(titles[i]);
// 將單元格加入樣式
cell1.setCellStyle(style2);
}
for (int i = 0; i < userlist.size(); i++) {
User user = userlist.get(i);
Row rowdata = sheet.createRow(i + 2);
// 姓名
Cell cell0 = rowdata.createCell(0);
cell0.setCellValue(user.getName());
// 賬號
Cell cell1 = rowdata.createCell(1);
cell1.setCellValue(user.getAccount());
// 部門
Cell cell2 = rowdata.createCell(2);
cell2.setCellValue(user.getDept());
// 性別
Cell cell3 = rowdata.createCell(3);
cell3.setCellValue(user.isGender() ? "男" : "女");
// 手機
Cell cell4 = rowdata.createCell(4);
cell4.setCellValue(user.getMobile());
// 電郵
Cell cell5 = rowdata.createCell(5);
cell5.setCellValue(user.getEmail());
// 生日
Cell cell6 = rowdata.createCell(6);
if(user.getBirthday()!=null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
cell6.setCellValue(sdf.format(user.getBirthday()));
}else{
cell6.setCellValue("");
}
}
// 6.寫入硬碟檔案
workbook.write(outputStream);
workbook.close();
}
//設定樣式方法
public static CellStyle createStyle(Workbook workbook,int fontsize){
//1.2設定單元格樣式
CellStyle style = workbook.createCellStyle();
// 設定水平居中
style.setAlignment(CellStyle.ALIGN_CENTER);
// 設定垂直居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 1.3設定字型
Font font = workbook.createFont();
// 設定字型為ARIAL
font.setFontName(HSSFFont.FONT_ARIAL);
// 設定粗體
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 設定字型顏色
//font.setColor(HSSFColor.BLUE.index);
// 設定字型大小
font.setFontHeightInPoints((short) fontsize);
// 將字型加入樣式
style.setFont(font);
return style;
}
excel上傳方法
public String importExcel(){
//先判斷上傳的檔案是不是excel
if(userExcelFileName.matches("^.+\\.(?i)(xls|xlsx)$")){
try {
userService.importExcel(userExcel,userExcelFileName);
} catch (Exception e) {
e.printStackTrace();
}
}
return "list";
}
//dervice中的方法
public void importExcel(File userExcel, String userExcelFileName) throws Exception {
FileInputStream fis = new FileInputStream(userExcel);
boolean b = userExcelFileName.matches("^.+\\.xlsx$");
//1.建立工作薄
Workbook workbook = null;
workbook=b?new XSSFWorkbook(fis):new HSSFWorkbook(fis);
//2.獲取工作表
Sheet sheet = workbook.getSheetAt(0);
int nums = sheet.getPhysicalNumberOfRows();
System.out.println(nums);
if(nums>2){
User user = null;
for(int i=2;i<nums;i++){
user = new User();
Row row = sheet.getRow(i);
//4.獲取單元格
Cell namecell = row.getCell(0);
String name = namecell.getStringCellValue();
user.setName(name);
Cell accountcell = row.getCell(1);
String account = accountcell.getStringCellValue();
user.setAccount(account);
Cell deptcell = row.getCell(2);
String dept = deptcell.getStringCellValue();
user.setDept(dept);
Cell gendercell = row.getCell(3);
String gender = gendercell.getStringCellValue();
user.setGender(gender.equals("男"));
Cell mobilecell = row.getCell(4);
String mobile = null;
try {
mobile = mobilecell.getStringCellValue();
} catch (Exception e) {
mobile = BigDecimal.valueOf(mobilecell.getNumericCellValue()).toString();
}
user.setMobile(mobile);
Cell emailcell = row.getCell(5);
String email = emailcell.getStringCellValue();
user.setEmail(email);
Cell birthdaycell = row.getCell(6);
String birthday = birthdaycell.getStringCellValue();
if(birthday!=null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
user.setBirthday(sdf.parse(birthday));
}
//設定使用者狀態
user.setState(User.USER_STATE_VALID);
//設定使用者預設密碼
user.setPassword("123456");
userDao.save(user);
}
}
}