java_项目_EasyPoi导入与导出

文章目录

    • 1 Java操作Excel
      • 1.1 概念
      • 1.2 JXL与POI优缺点
      • 1.3 引入poi需要的jar包
      • 1.4 创建Excel(完成99乘法表)
      • 1.5 java读取Excel
    • 2 EasyPoi使用
      • 2.1 引入easypoi的jar包
      • 2.2 基本导出
      • 2. 3员工页面 Employee.jsp 加上导出按钮
      • 2.4 EmployeeController添加方法
    • 3 EasyPoi导入功能
      • 3.1 ImportController添加功能
      • 3.2 自定义验证功能

1 Java操作Excel

1.1 概念

jxl:只能对Excel进行操作,属于比较老的框架。
POI:是apache的项目,可对ms的word,Excel,PPT进行操作,包括office2003和2007。对两种版本的处理都比较好。具体操作请看官方的文档
java_项目_EasyPoi导入与导出_第1张图片

1.2 JXL与POI优缺点

JXL优点(韩国人开发):

  1. Jxl对中文支持非常好,操作简单,方法看名知意。
  2. Jxl是纯javaAPI,在跨平台上表现的非常完美,代码可以再windows或者Linux上运行而无需重新编写
  3. 支持Excel 95-2000的所有版本(网上说目前可以支持Excel2007了,还没有尝试过)
  4. 生成Excel 2000标准格式
  5. 支持字体、数字、日期操作
  6. 能够修饰单元格属性
  7. 支持图像和图表,但是这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

缺点:效率低,图片支持不完善,对格式的支持不如POI强大

POI优点:

  1. 效率高
  2. 支持公式,宏,一些企业应用上会非常实用
  3. 能够修饰单元格属性
  4. 支持字体、数字、日期操作
  5. 支持03和07的版本

缺点:不成熟,代码不能跨平台,兼容性不是那么好

1.3 引入poi需要的jar包


<dependency>
 <groupId>org.apache.poigroupId>
 <artifactId>poiartifactId>
 <version>3.11version>
dependency>
<dependency>
 <groupId>org.apache.poigroupId>
 <artifactId>poi-ooxmlartifactId>
 <version>3.11version>
dependency>

1.4 创建Excel(完成99乘法表)

//导入
@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();
    }
}

1.5 java读取Excel

/**
 * 读取我们使用相应的方案
 * @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();
    }
}

2 EasyPoi使用

2.1 引入easypoi的jar包

特别注意:把之前咱们的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>

2.2 基本导出

在字段上面添加注解

@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;

2. 3员工页面 Employee.jsp 加上导出按钮

<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>

2.4 EmployeeController添加方法

@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" />

3 EasyPoi导入功能

3.1 ImportController添加功能

@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";
    }
}

3.2 自定义验证功能

扫描它,把它交给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;
    }
}

你可能感兴趣的:(学习)