今天目标:
(1)把系统的数据 导出到excel里面
(2) 把excel数据导入到系统
1.操作excel的使用场景(理解)
(1) excel和word这些都是办公的软件,但是有时候系统需要结合办公软件来使用,比如经常用户要求查询
最近5年的销售情况,最近一个人新增的人数 -->通过软件导出到excel表格里面,编辑起来很容易 --打印出来
(2)系统里面哪些地方可以使用excel或者word?
豪哥:招聘网站 --在线去编辑简历 – 导出来word–打印出来
豪哥: 收入情况 – 工资 数据–导出excel
批量录入信息。–有很多数据 在做软件之前已经产生,软件开发完,把 以前的数据录入到系统
批量导入数据功能–excel–>程序–》数据库表
2.完成导入导出操作 怎么去做?(理解)
今天目标:
(1)把系统的数据 导出到excel里面
(2) 把excel数据导入到系统
完成这个目标:
怎么去做?
学习Java去操作办公软件的框架
现在流行的两款操作办公软件的框架
jxl: jxl早期只对excel操作,在处理excel上面有很多的优势 jxl在写入上要快一点
poi:excel和word,ppt都可以才有 poi在读取上面要快一点
JXL优点(韩国人开发):
- Jxl对中文支持非常好,操作简单,方法看名知意。
- Jxl是纯javaAPI,在跨平台上表现的非常完美,代码可以再windows或者Linux上运行而无需重新编写
- 支持Excel 95-2000的所有版本(网上说目前可以支持Excel2007了,还没有尝试过)
- 生成Excel 2000标准格式
- 支持字体、数字、日期操作
- 能够修饰单元格属性
- 支持图像和图表,但是这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。
缺点:效率低,图片支持不完善,对格式的支持不如POI强大
POI优点:
- 效率高(数据来源:http://blog.csdn.net/jarvis_java/article/details/4924099)
- 支持公式,宏,一些企业应用上会非常实用
- 能够修饰单元格属性
- 支持字体、数字、日期操作
- 支持03和07的版本
缺点:不成熟,代码不能跨平台,兼容性不是那么好
记住2-3点
3 学习POI
其实poi对03(xls)和07(xlsx)写了两套api这个两个版本
4 使用原生poi完成9*9乘法表–导出(练习)
excel组成:
多个sheet组成 – excel表格
1一个sheet有行row 和 列col组成
行row由单元格组成 --cell
[外链图片转存失败(img-p82XIeSX-1566051215950)(C:\Users\0427\AppData\Roaming\Typora\typora-user-images\1565404413103.png)]
//创建一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个表格
XSSFSheet sheet = workbook.createSheet("99乘法表");
for (int i = 1; i <=9 ; i++) {
//9行 1*1
// 1*2 2*2
XSSFRow row = sheet.createRow(i-1);
for (int j = 1; j <= i ; j++) {
//创建一个单元格
XSSFCell cell = row.createCell(j-1);
cell.setCellValue(i+"*"+j+"="+(i*j));
}
}
//输出
FileOutputStream out = new FileOutputStream(
new File("99.xlsx"));
workbook.write(out);
out.close();
5 通过poi读取的excel数据–导入(练习)
//读取
FileInputStream fis = new FileInputStream(
new File("empread.xlsx"));
//得到工作薄
XSSFWorkbook workbook = new XSSFWorkbook(fis);
//得到第一个表格
XSSFSheet spreadsheet = workbook.getSheetAt(0);
//获取表格所有的row
Iterator <Row> rowIterator = spreadsheet.iterator();
int count = 0;
//循环行
while (rowIterator.hasNext()) {
count++;
//取出具体哪一个行
XSSFRow row = (XSSFRow) rowIterator.next(); //取出两行进行抛弃
if (count > 2) {
//得到单元格
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
//取出单元格
Cell cell = cellIterator.next();
//判断单元格类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(
cell.getNumericCellValue() + " \t\t ");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(
cell.getStringCellValue() + " \t\t ");
break;
}
}
System.out.println();
}
}
fis.close();
}
6 easypoi的操作(掌握)
6.1 基本导出
在字段上面添加注解
@Excel(name=“列的名称”)
性别
@Excel(name=“性别”,replace = {“男_true”,“女_false”})
日期
@Excel(name=“出生日期”,format = “yyyy-MM-dd”)
图片
@Excel(name=“头像”,type = 2 ,width = 40 , height = 20)
关联对象
@ExcelEntity
private EasyDept easyDept;
需求:如果员工表格 导出是部门名称 没有问题 如果我只想导出部门
@ExcelTarget("emp1")
public class EasyEmployee{
@ExcelEntity
private EasyDept easyDept;//导出额外属性
}
//注意:如果只导出一列,不要添加title,多列就可以添加
//Workbook workbook = ExcelExportUtil.exportExcel(new //ExportParams("qwe2qweqweqwe","4444111"),EasyDept.class, list);
@ExcelTarget("dept")
public class EasyDept {
@Excel(name="部门名称111_emp1,名称_dept")
private String name;
@Excel(name="部门地址111_emp1,地址_dept")
private String address;
}
测试代码
@Test
public void testEasyuiPoi3() throws Exception{
List<EasyDept> list = new ArrayList<>();
EasyDept easyDept = new EasyDept();
easyDept.setName("测试123");
easyDept.setAddress("少林寺");
list.add(easyDept);
//导出代码
//ExportParams 设置标题 设置表名
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("qwe2qweqweqwe","4444111"),EasyDept.class, list);
//输出效果
FileOutputStream outputStream = new FileOutputStream("employee2222.xlsx");
workbook.write(outputStream);
outputStream.close();
}
6.2 和springmvc集成导出(掌握)
@RequestMapping("/download")
public String download(ModelMap map, EmployeeQuery employeeQuery, HttpServletRequest request){
System.out.println("-------------------------------");
//查询数据出来
List<Employee> employees = employeeService.findByQuery(employeeQuery);
String path = request.getServletContext().getRealPath("/");
for (Employee employee : employees) {
employee.setHeadImage(path+employee.getHeadImage());
System.out.println(employee.getHeadImage());
}
//导出参数设置 ExportParams
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, "employeefileName");//文件名称
//easypoiExcelView easypoiExcelView --本身spring有一个视图解析器,
//返回字符串就给我返回对应页面
return NormalExcelConstants.EASYPOI_EXCEL_VIEW;//View名称
}
springmvc配置视图解析器顺序
<!-- 扫描easypoi的视图处理包-->
<context:component-scan base-package="cn.afterturn.easypoi.view"></context:component-scan>
<!-- 优先找easypoi的视图解析器-->
<!-- bean的视图解析器 p:order="0": 顺序在最前面 -->
<bean id="beanNameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"
p:order="0" />
6.3导入功能(掌握)
//具备验证功能
@RequestMapping("/employeeXlsx")
public String employeeXlsx(MultipartFile empFile, HttpServletResponse response) throws Exception {
//这个文件怎么
ImportParams params = new ImportParams();
params.setTitleRows(1);
//开启验证
params.setNeedVerfiy(true);
//开启自定义验证
params.setVerifyHandler(aisellEmployeeVerifyHander);
//导入
ExcelImportResult<Employee> result = ExcelImportUtil.importExcelMore(empFile.getInputStream(),
Employee.class, params);
//正确数据
for (Employee employee : result.getList()) {
System.out.println(employee);
//根据部门名称查询的部门对象
String deptName = employee.getDepartment().getName();
Department department = departmentService.findDepartmentByName(deptName);
//设置部门
employee.setDepartment(department);
employee.setPassword("123456");
//System.out.println(employee.getDepartment().getName());
employeeService.save(employee);
}
//错误的数据
for (Employee employee : result.getFailList()) {
System.out.println("错误数据:"+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";
}
自定义验证
@Component
public class AisellEmployeeVerifyHander implements IExcelVerifyHandler<Employee> {
@Autowired
private IEmployeeService employeeService;
@Override
public ExcelVerifyHandlerResult verifyHandler(Employee employee) {
//employee就导入的时候传过来的数据 如果什么都没有处理 返回true --通过
//如果检测失败之后,返回false 并且设置信息
ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult(true);
//返回true 通过 否则false 就重复
boolean flag = employeeService.checkUsername(employee.getUsername());
if(!flag){
result.setSuccess(false);
result.setMsg("用户名重复");
}
return result;
}
}