Excel导入导出

Posted 1999wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel导入导出相关的知识,希望对你有一定的参考价值。

                    Excel导入导出

jxl:只能对Excel进行操作,属于比较老的框架

 

 

POI:是apache的项目,可对msword,Excel,PPT进行操作,包括office20032007。对两种版本的处理都比较好。具体操作请看官方的文档。

 

excel的使用场景:excel和word这些都是办公的软件,但是有时候系统需要结合办公软件来使用,比如经常用户要求查询

那些部门的销售情况销和人数的时候

 

poi的使用:引入需要的 包

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.11</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.11</version>
</dependency>

完成一个99乘法表的导出:

 

public void testPoiWrite99() throws Exception
//创建一个工作薄
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();

SpringMVC  POI整合导入导出:

SpringMVC上传配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize">
        <value>1048576</value>
    </property>
</bean>

 

准备上传的按钮:

 

<form id="searchForm" action="/employee/download" method="post">
用户名: <input name="username" class="easyui-textbox" style="width:80px;height:32px">
邮件: <input name="email" class="easyui-textbox" style="width:80px;height:32px">
部门 :
<input class="easyui-combobox" name="departmentId"
data-options="valueField:‘id‘,textField:‘name‘,panelHeight:‘auto‘,url:‘/util/departmentList‘">
<a href="#" data-method="search" class="easyui-linkbutton" iconCls="icon-search">查找</a>
<%--默认提交到form表单路劲--%>
<button class="easyui-linkbutton" iconCls="icon-redo">导出</button>
</form>

<form></form>标签提交的路劲导controller层

@RequestMapping("/import")
public class ImportController extends BaseController

//跳转到导入页面
@RequestMapping("/index")
public String index()
return "import";


//跳转到导入页面
@RequestMapping("/xlsx")
public String importXlsx(MultipartFile xlsxFile) throws Exception
System.out.println(xlsxFile.getContentType()); //文件的类型(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
System.out.println(xlsxFile.getName()); //文件的名称(xlsxFile)
System.out.println(xlsxFile.getOriginalFilename());//文件的名称(employee-3.xlsx)
System.out.println(xlsxFile.getSize()); //文件的大小
return "import";

准备上传的一个方法:

public static List<String[]> importExcel(InputStream is) throws Exception
//.准备装数据的容器
List<String[]> list = new ArrayList<>();
//1.读取一个Excel文件(内存中)
Workbook wb = new XSSFWorkbook(is);
//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();
//.准备一个String[]装一行数据(有几列就有几条数据)
String[] data = new String[lastCellNum];
for (int j = 0; j < lastCellNum; j++)
Cell cell = row.getCell(j);
data[j] = cell.getStringCellValue();

//.把一行数据写到集合中去
list.add(data);

return list;

最后成功了给出提示:

@RequestMapping("/xlsx")
public String importXlsx(MultipartFile xlsxFile, Model model) throws Exception
//拿到上传的数据
List<String[]> list = ExcelUtils.importExcel(xlsxFile.getInputStream());
int count = 0;
for (int i = 0; i < list.size(); i++)
//拿到每一行数据
String[] data = list.get(i);
//准备Employee对象进行数据放置
Employee employee = new Employee();
employee.setUsername(data[0]+ UUID.randomUUID().toString().substring(0,5));//随机一个名称
employee.setPassword(data[1]);
employee.setEmail(data[2]);
String age = data[3];
if(StringUtils.isNotBlank(age))
employee.setAge(Integer.parseInt(age));

//拿到与设置部门
String deptName = data[4];
if(StringUtils.isNotBlank(deptName))
Department department = departmentService.findByName(deptName)[这个方法需要根据用户名去拿到相应的部门,我们不在笔记中体现与完成这个方法,希望同学们是可以自己把这个简单的小功能补齐!];
employee.setDepartment(department);

employeeService.save(employee);
count ++;

//给出成功提示
model.addAttribute("count","成功导入"+count+"条数据!");
return "import";

springMVC导入:

准备一个导入页面:


<html>
<head>
<title>Title</title>
<%@include file="/WEB-INF/views/head.jsp" %>
</head>
<body>
<!-- 上传必需是:postenctype="multipart/form-data"-->
<form action="/import/employeeXlsx" method="post" enctype="multipart/form-data">
<input class="easyui-filebox" name="empFile" style="width:80%"
data-options="prompt:‘选择一个文件...‘,buttonText: ‘选择文件‘" />
<button class="easyui-linkbutton">导入</button>
</form>
</body>
</html>
 

准备一个你要导入的文档:

进入controller层读取你要导入的文档最

 

@RequestMapping("/employeeXlsx1")
public String employeeXlsx1(MultipartFile empFile) throws Exception

ImportParams params = new ImportParams();
params.setTitleRows(1);

//导入
List<Employee> list = ExcelImportUtil.importExcel(empFile.getInputStream(),
Employee.class, params);

for (Employee employee : list)
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);




return "import";

 最后添加验证功能:

//开启验证
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);

 

最后把导入的信息添加到数据库然后展示到页面上让用户查看:

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

 

以上是关于Excel导入导出的主要内容,如果未能解决你的问题,请参考以下文章

EasyExcel导入、导出Excel

如何实现SpreadJS的纯前端Excel导入导出

请教如何用JQuery导入导出excel表格

实现excel导入导出功能,excel导入数据到页面中,页面数据导出生成excel文件

vue项目实现导入/导出Excel

.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)