一、前提条件
POI组件基础知识,POI操作Excel文档、读取、写入、合并单元格。(点击查看)
SSM框架整合Maven工程整合Spring+Springmvc+Mybatis(详细教程,附代码)(点击查看)
二、POI与SSM框架整合实现Excel导入
1、Maven工程pom.xml文件中添加Excel导入所需依赖包
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.16</version>
</dependency>
<!-- 文件上传类 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
2、修改spring-mvc.xml增加文件上传配置
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
3、编写Excel上传处理控制类Controller层
@Controller
public class FileUploadController {
@Autowired
NewStudentInfoService newStudentInfoService;
@RequestMapping(value="/importexcel",method=RequestMethod.POST)
public String uploadExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request,Model model){
//获取服务器端路径
String path=request.getServletContext().getRealPath("upload");
//获取到上传文件名称
String fileName=file.getOriginalFilename();
//创建目标File
File targetFile=new File(path+"\\"+fileName);
//创建存储目录
File targetPath=new File(path);
//判断服务器端目录是否存在,如果不存在创建目录
if(!targetPath.exists()){
targetPath.mkdir();
}
//把上传的文件存储到服务器端
try {
file.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//读取上传到服务器端的文件,遍历excel
try {
Workbook workbook=WorkbookFactory.create(targetFile);
Sheet sheet = workbook.getSheet("Sheet1");
//判断行数
int rownum = sheet.getPhysicalNumberOfRows();
for(int i=0;i<rownum;i++){
Row row = sheet.getRow(i);
//判断单元格数量
int cellnum = row.getPhysicalNumberOfCells();
StringBuffer buf=new StringBuffer();
for(int j=0;j<cellnum;j++){
Cell cell = row.getCell(j);
if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
buf.append(cell.getStringCellValue()+"~");
}else if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
//创建数字格式化工具类
DecimalFormat df=new DecimalFormat("####");
//把从cell单元格读取到的数字,进行格式化防止科学计数法形式显示
buf.append(df.format(cell.getNumericCellValue())+"~");
}
}
//单元格循环完成后读取到的是一行内容 1~xingming~88
String hang=buf.toString();
String[] rows=hang.split("~");
NewStudent stu=new NewStudent();
stu.setName(rows[1]);
stu.setScore(Integer.valueOf(rows[2]));
stu.setPhone(rows[3]);
System.out.println("上传学生信息:"+stu);
newStudentInfoService.saveStudent(stu);
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
return "sucess";
}
4、Service层
public interface NewStudentInfoService {
public int save(NewStudent newStudent);
public List<NewStudent> getAllStu();
}
@Service
public class NewStudentInfoServiceImpl implements NewStudentInfoService {
@Autowired
NewStudentInfoDao newStudentInfoDao;
@Override
public int save(NewStudent newStudent) {
return newStudentInfoDao.save(newStudent);
}
@Override
public List<NewStudent> getAllStu() {
List<NewStudent> allStudents = newStudentInfoDao.getAllStudents();
return allStudents;
}
}
5、Dao层——以一个简单的小例子为案例
public interface NewStudentInfoDao {
public int save(NewStudent newStudent);
public List<NewStudent> getAllStudents();
}
6、mapper*.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zxh.Dao.NewStudentInfoDao">
<insert id="save" parameterType="com.zxh.pojo.NewStudent">
INSERT INTO person (NAME,age,phone) VALUE(#{name},#{age},#{phone})
</insert>
<select id="getAllStudents" resultType="com.zxh.pojo.NewStudent">
SELECT * FROM person
</select>
</mapper>
7、编写JSP页面excelupload.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="downloadexcel">导出Excel</a>
</br></br></br></br>
<form action="importexcel" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
8、编写JSP页面sucess.jsp 存放在:WEB-INF/jsp目录下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="text-align:center">
上传文件成功!</div>
</body>
</html>
9、数据库
/*!40101 SET NAMES utf8 */;
create table `person` (
`id` int (9),
`name` varchar (36),
`age` varchar (27),
`phone` varchar (48)
);
10、测试运行——导入Excel文件
数据库中得到上传的信息
三、POI与SSM框架整合实现Excel导出
1、编写Excel导出Controller
@Controller
public class OutPutExcel {
@Autowired
NewStudentInfoService newStudentInfoService;
@RequestMapping(value = "/downloadexcel")
public ResponseEntity<byte[]> down(HttpServletRequest request, HttpServletResponse response, Model model)
throws IOException {
System.out.println("111111111");
// 从数据库读取数据
List<NewStudent> allStu = newStudentInfoService.getAllStu();
// 获取服务路径
String path = request.getServletContext().getRealPath("down");
String filename = "demo.xlsx";
// 存储File
File tfile = new File(path + "\\" + filename);
// 目录
File mfile = new File(path);
if (!tfile.exists()) {
mfile.mkdir();
}
// 生成excel
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("学员信息表");
int rownum = 0;
for (NewStudent stu : allStu) {
XSSFRow row = sheet.createRow(rownum);
row.createCell(0).setCellValue(stu.getName());
row.createCell(1).setCellValue(stu.getName());
row.createCell(2).setCellValue(stu.getAge());
row.createCell(3).setCellValue(stu.getphone());
rownum++;
}
// 保存workbook
try {
workbook.write(new FileOutputStream(tfile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 创建请求头对象
HttpHeaders headers = new HttpHeaders();
// 下载显示的文件名,解决中文名称乱码问题
String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
// 通知浏览器以attachment(下载方式)打开
headers.setContentDispositionFormData("attachment", downloadFileName);
// application/octet-stream:二进制流数据(最常见的文件下载)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(tfile),
headers, HttpStatus.CREATED);
return responseEntity;
}
}
2、Excel导出设置