Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出

一、前提条件

POI组件基础知识,POI操作Excel文档、读取、写入、合并单元格。(点击查看)

SSM框架整合Maven工程整合Spring+Springmvc+Mybatis(详细教程,附代码)(点击查看)

二、POI与SSM框架整合实现Excel导入

1、Maven工程pom.xml文件中添加Excel导入所需依赖包


		
            org.apache.poi
            poi
            3.16
        
        
            org.apache.poi
            poi-ooxml-schemas
            3.16
        
        
            org.apache.poi
            poi-excelant
            3.16
                
        
		 
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
            commons-io
            commons-io
            2.1
        			

2、修改spring-mvc.xml增加文件上传配置

 
      
           
          
          
     

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

 4、Service层

public interface NewStudentInfoService {

	public int save(NewStudent newStudent);

	public List getAllStu();
}

 

@Service
public class NewStudentInfoServiceImpl implements NewStudentInfoService {

	@Autowired
	NewStudentInfoDao newStudentInfoDao;
	@Override
	public int save(NewStudent newStudent) {
		return newStudentInfoDao.save(newStudent);
	}
	@Override
	public List getAllStu() {
		List allStudents = newStudentInfoDao.getAllStudents();
		return allStudents;
	}
}

5、Dao层——以一个简单的小例子为案例

public interface NewStudentInfoDao {

	public int save(NewStudent newStudent);

	public List getAllStudents();
	 
}

6、mapper*.xml




	
		INSERT INTO person (NAME,age,phone) VALUE(#{name},#{age},#{phone})
	
	

7、编写JSP页面excelupload.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here



导出Excel




8、编写JSP页面sucess.jsp  存放在:WEB-INF/jsp目录下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 




Insert title here


上传文件成功!

9、数据库 

/*!40101 SET NAMES utf8 */;

create table `person` (
	`id` int (9),
	`name` varchar (36),
	`age` varchar (27),
	`phone` varchar (48)
); 

10、测试运行——导入Excel文件

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第1张图片

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第2张图片

数据库中得到上传的信息

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第3张图片

三、POI与SSM框架整合实现Excel导出

1、编写Excel导出Controller

@Controller
public class OutPutExcel {

	@Autowired
	NewStudentInfoService newStudentInfoService;

	@RequestMapping(value = "/downloadexcel")
	public ResponseEntity down(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		System.out.println("111111111");
		// 从数据库读取数据
		List 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 responseEntity = new ResponseEntity(FileUtils.readFileToByteArray(tfile),
				headers, HttpStatus.CREATED);
		return responseEntity;
	}
}

2、Excel导出设置

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第4张图片

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第5张图片

Java实战—POI 与SpringMVC框架(SSM框架)整合实现Excel导入导出_第6张图片

 

你可能感兴趣的:(Java)