Java實戰—POI 與SpringMVC框架(SSM框架)整合實現Excel導入導出

一、前提條件

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導出設置

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章