您的位置:首页 > 其它

头像上传与使用POI导入导出文件列表

2016-08-09 20:15 399 查看

一、头像上传

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导入导出文件列
4000

差点忘了准备工作,导入相关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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: