jxl:只能对Excel进行操作,属于比较老的框架。
POI:是apache的项目,可对ms的word,Excel,PPT进行操作,包括office2003和2007。对两种版本的处理都比较好。具体操作请看官方的文档
JXL优点(韩国人开发):
缺点:效率低,图片支持不完善,对格式的支持不如POI强大
POI优点:
缺点:不成熟,代码不能跨平台,兼容性不是那么好
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>3.11version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>3.11version>
dependency>
//导入
@Test
public void readExcel()throws Exception{
//读取文件
FileInputStream fis = new FileInputStream(new File("empread.xlsx"));
//得到工作薄
Workbook wb = new XSSFWorkbook(fis);
//2.拿到第个sheet表
Sheet sheet = wb.getSheetAt(0);
//3.拿到wb中的行(不要拿头部)
int lastRowNum = sheet.getLastRowNum();
for (int i = 2; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
//4.拿到每一列(格子)
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
}
/**
* 读取我们使用相应的方案
* @throws Exception
*/
@Test
public void readExcel() throws Exception{
File file = new File("employee-3.xlsx");
FileInputStream fis = new FileInputStream(file);
//1.读取一个Excel文件(内存中)
Workbook wb = new XSSFWorkbook(fis);
//2.拿到第个sheet表
Sheet sheet = wb.getSheetAt(0);
//3.拿到wb中的行(不要拿头部)
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
//4.拿到每一列(格子)
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
}
特别注意:把之前咱们的POI引入去掉(有冲突)
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-baseartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-webartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-annotationartifactId>
<version>3.2.0version>
dependency>
在字段上面添加注解
@Entity
@Table(name="employee")
public class Employee extends BaseDomain {
@Excel(name="用户名")
private String username;
private String password;
@Excel(name="邮件",width = 25)
private String email;
@Excel(name="年纪")
private Integer age;
@Excel(name = "头像",type = 2,savePath = "/images/head",height = 23)
private String headImage; //头像
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="department_id")
//Json Ignore(忽略) Properties(属性)
//@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
@ExcelEntity
private Department department;
...
部门有相应的关连
@Entity
@Table(name="department")
public class Department extends BaseDomain {
@Excel(name = "部门名称")
private String name;
<form id="searchForm" action="/employee/download">
用户名: <input name="username" class="easyui-textbox" style="width:80px">
邮件: <input name="email" class="easyui-textbox" style="width:80px">
部门:<input name="departmentId" class="easyui-combobox" name="dept"
panelHeight="auto"
data-options="valueField:'id',textField:'name',url:'/util/dept'" />
<a href="#" class="easyui-linkbutton" data-method="search" iconCls="icon-search">查询</a>
<!-- button不加type属性就是提交 -->
<button class="easyui-linkbutton" iconCls="icon-search">导出</button>
</form>
@RequestMapping("/download")
public String download(ModelMap map , EmployeeQuery employeeQuery, HttpServletRequest request){
List<Employee> employees = employeeService.findByQuery(employeeQuery);
String realPath = request.getServletContext().getRealPath("");
for (Employee employee : employees) {
employee.setHeadImage(realPath+employee.getHeadImage());
}
//设置一些属性
ExportParams params = new ExportParams("员工管理", "明细", ExcelType.XSSF);
//冻结列
params.setFreezeCol(2);
map.put(NormalExcelConstants.DATA_LIST, employees); // 数据集合
map.put(NormalExcelConstants.CLASS, Employee.class);//导出实体
map.put(NormalExcelConstants.PARAMS, params);//参数
map.put(NormalExcelConstants.FILE_NAME, "employee");//文件名称
//返回字符串就给我们返回对应的页面
return NormalExcelConstants.EASYPOI_EXCEL_VIEW;//View名称
//return "forward:/WEB-INF/views/employee.jsp";
}
特别注意:要使用 return NormalExcelConstants.EASYPOI_EXCEL_VIEW
spring的.xml 需要加上
<context:component-scan base-package="cn.afterturn.easypoi.view" />
<bean id="beanNameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"
p:order="0" />
@Controller
@RequestMapping("/import")
public class ImportController {
@Autowired
private IDepartmentService departmentService;
@Autowired
private AisellEmployeeVerifyHander aisellEmployeeVerifyHander;
@Autowired
private IEmployeeService employeeService;
@RequestMapping("/index")
public String importPage(){
return "import";
}
//导入功能
@RequestMapping("/employeeXlsx")
public String employeeXlsx(MultipartFile empFile, HttpServletResponse response) throws Exception {
//处理上传文件
ImportParams params = new ImportParams();
params.setTitleRows(1);
//开启验证
params.setNeedVerfiy(true);
//开启自定义验证
params.setVerifyHandler(aisellEmployeeVerifyHander);
//excel导入的一个结果
ExcelImportResult<Employee> result = ExcelImportUtil.importExcelMore(
empFile.getInputStream(),
Employee.class, params);
for (Employee employee : result.getList()) {
//根据部门查询部门对象
String deptName = employee.getDepartment().getName();
Department department = departmentService.findDepartmentByName(deptName);
//设置部门
employee.setDepartment(department);
employee.setPassword("123");
//保存数据
employeeService.save(employee);
}
//错误的数据
if(result.isVerfiyFail()){
Workbook failWorkbook = result.getFailWorkbook();
//把这个文件导出
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //mime类型
response.setHeader("Content-disposition", "attachment;filename=error.xlsx");
response.setHeader("Pragma", "No-cache");//设置不要缓存
OutputStream ouputStream = response.getOutputStream();
failWorkbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
return "import";
}
}
扫描它,把它交给Spring管理
<context:component-scan base-package="cn.itsource.aisell.common" />
准备java类AisellEmployeeVerifyHander
@Component
public class AisellEmployeeVerifyHander implements IExcelVerifyHandler<Employee> {
@Autowired
private IEmployeeService employeeService;
@Override
public ExcelVerifyHandlerResult verifyHandler(Employee employee) {
//employee导入的时候 传过来的数据
ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult(true);
//如果什么都没有处理 通过 返回true
//如果检测失败过后 返回false 并且设置信息
boolean flag = employeeService.checkUsername(employee.getUsername());
if (!flag){
result.setMsg("用户名重复");
result.setSuccess(false);
}
return result;
}
}