【Java】SpringMVC整合poi实现excel的导入导出

1.官网:https://poi.apache.org/
2.特点:

结构: 

HSSF - 提供读写Microsoft Excel格式档案的功能。 

XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。 

HWPF - 提供读写Microsoft Word格式档案的功能。 

HSLF - 提供读写Microsoft PowerPoint格式档案的功能。 

HDGF - 提供读写Microsoft Visio格式档案的功能。

springmvc整合poi过程记录

3.pom.xml整合

<dependency>
    <groupId>org.apache.poigroupId>
    <artifactId>poiartifactId>
    <version>3.17version>
dependency>

如果涉及到了文件上传,需要配置这个

<dependency>
	<groupId>commons-fileuploadgroupId>
	<artifactId>commons-fileuploadartifactId>
	<version>1.3version>
dependency>
<dependency>
	<groupId>commons-iogroupId>
	<artifactId>commons-ioartifactId>
	<version>2.2version>
dependency>
4.applicationContext.xml里面

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
5.使用
package com.naton.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.alibaba.fastjson.JSONObject;
import com.naton.advice.exception.ServiceException;
import com.naton.pojo.vo.PageExample;
import com.naton.service.ExcelService;
import com.naton.util.json.JSONMessage;


@Controller
@RequestMapping("/excel/Service")
public class ExcelController {
	
	@Autowired 
	private ExcelService excelService;
	
	
	/**
	 * 下载导入模板
	 * @param response
	 * @param param
	 */
	@ResponseBody
	@RequestMapping("/downloadTemplate")
	public void downloadTemplate(HttpServletResponse response, HttpSession session) {
		OutputStream out = null;
        InputStream in = null;
        
        try {
			String fileName = "BaseData.xls";
			String localPath = session.getServletContext().getRealPath("/upload");
			
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition","attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO_8859_1"));
			
			File in_file = new File(localPath + "/" + fileName);
	    	in = new FileInputStream(in_file);
	    	
	        out = response.getOutputStream();
			byte[] tmp = new byte[1024];
			while (in.read(tmp) != -1) {
				out.write(tmp);
			}
			out.flush();
			in.close();
			return ;
		} catch (IOException e) {
			e.printStackTrace();
			throw new ServiceException("模板下载失败  "+e.getMessage());
		}
	}
	/**
	 * 上传文件
	 * @param request
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadData",method=RequestMethod.POST)
    public JSONObject uploadData(HttpServletRequest request,@RequestParam MultipartFile file){
        //手工导入
        try {
            MultipartRequest multipartRequest=(MultipartRequest) request;
            MultipartFile excelFile=multipartRequest.getFile("file");
            if(excelFile!=null  && excelFile.getSize() > 0){
            	
            	int i = -1;
                i = excelService.insertDBByExcel(excelFile);
                
                if(i == 0){
                    return JSONMessage.success("内容为空", i); 
                }else if(i > 0){
                	return JSONMessage.success("导入成功", i); 
                }else{
                    return JSONMessage.failure("导入失败"); 
                }
            }else{
                return JSONMessage.success("上传失败", null); 
            }
        } catch (Exception e) {
            throw new ServiceException("上传文件出错");
        }
    }
	/**
	 * 导出数据
	 * @param response
	 * @param param
	 * @return
	 */
    @ResponseBody
	@RequestMapping(value = "/exportData", method = RequestMethod.GET)
    public JSONObject exportData(HttpServletResponse response,@ModelAttribute PageExample param){

		try {
			excelService.exportToExcel(response, param);
		} catch (Exception e) {
			throw new ServiceException("导出失败");
		}
        
        return JSONMessage.success("导出成功", null); 
    }
	
	
}
package com.naton.service;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.naton.pojo.vo.PageExample;

public interface ExcelService {

	int insertDBByExcel(MultipartFile excelFile);

	void exportToExcel(HttpServletResponse response, PageExample param);
	
}
package com.naton.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.naton.advice.exception.ServiceException;
import com.naton.pojo.vo.PageExample;
import com.naton.service.ExcelService;

@Service
public class ExcelServiceImpl implements ExcelService{

	
	@Override
	public int insertDBByExcel(MultipartFile excelFile) {
		int count = 0;
		try {
			//使用POI解析Excel文件  
			HSSFWorkbook book = new HSSFWorkbook(excelFile.getInputStream());
			//根据名称获得指定Sheet对象  
			HSSFSheet  hssfSheet = book.getSheet("数据");
			if (hssfSheet != null) {
					System.out.println(hssfSheet.getLastRowNum());
				for (Row row : hssfSheet) {  
		            //获取每一行的每个单元格  
		            String id = row.getCell(0).getStringCellValue();  
		            String province = row.getCell(1).getStringCellValue();  
		              
		            System.out.println(id + province  +"--");
		            
		            count++;
		        }  
				}
				// 正式导入数据库
				
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		
		return count;
	}

	@Override
	public void exportToExcel(HttpServletResponse response, PageExample param) {
		ServletOutputStream out = null;
		try {
			//第一步:查询所有的数据  
			List<String> list = new ArrayList<>();
			list.add("a6");
			list.add("a7");
			list.add("a8");
			list.add("a9");
			  
			//第二步:使用POI将数据写到Excel文件中  
			//在内存中创建一个Excel文件  
			@SuppressWarnings("resource")
			HSSFWorkbook workBook = new HSSFWorkbook();  
			//创建一个标签页  
			HSSFSheet sheet = workBook.createSheet("数据");  
			//创建标题行  
			HSSFRow headRow = sheet.createRow(0);  
			headRow.createCell(0).setCellValue("编号1");  
			headRow.createCell(1).setCellValue("编号2");  
			  
			for (String str : list) {  
			    HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);  
			    dataRow.createCell(0).setCellValue("city");  
			    dataRow.createCell(1).setCellValue(str);  
			}  
			  
			// 文件名
			StringBuffer fileName = new StringBuffer("export_");
			fileName.append(System.currentTimeMillis() / 1000);
			fileName.append(".xls");
			
			out = response.getOutputStream();
			//获取客户端浏览器类型  
			response.setHeader("content-disposition", "attachment; filename=\""
					+ new String(fileName.toString().getBytes("utf-8"),
							"ISO8859_1") + "\"");
			
			workBook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

以上便是一个简单的基于poi实现excel导入导出的例子。


你可能感兴趣的:(SpringMVC)