1. 程式人生 > >Java poi+excel匯入

Java poi+excel匯入

用的SSM框架,所需要的jar包如圖所示:,連結地址:jar包下載  ,下面直接上程式碼。

1、ExcelUtil工具類

<span style="color:#993399;"><span style="font-size:18px;color:#993399;">import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;

/**
 * Excel工具類
 * @author lp
 *
 */
public class ExcelUtil {
	public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
	public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
	public static final String EMPTY = "";
	public static final String POINT = ".";
	public static SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd");
	/**
	 * 獲得path的字尾名
	 * @param path
	 * @return
	 */
	public static String getPostfix(String path){
		if(path==null || EMPTY.equals(path.trim())){
			return EMPTY;
		}
		if(path.contains(POINT)){
			return path.substring(path.lastIndexOf(POINT)+1,path.length());
		}
		return EMPTY;
	}
	/**
	 * 單元格格式
	 * @param hssfCell
	 * @return
	 */
	@SuppressWarnings({ "static-access", "deprecation" })
	public static String getHValue(HSSFCell hssfCell){
		 if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			 return String.valueOf(hssfCell.getBooleanCellValue());
		 } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			 String cellValue = "";
			 if(HSSFDateUtil.isCellDateFormatted(hssfCell)){				
				 Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
				 cellValue = sdf.format(date);
			 }else{
				 DecimalFormat df = new DecimalFormat("#.##");
				 cellValue = df.format(hssfCell.getNumericCellValue());
				 String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
				 if(strArr.equals("00")){
					 cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
				 }	
			 }
			 return cellValue;
		 } else {
			return String.valueOf(hssfCell.getStringCellValue());
		 }
	}
	/**
	 * 單元格格式
	 * @param xssfCell
	 * @return
	 */
	public static String getXValue(XSSFCell xssfCell){
		 if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			 return String.valueOf(xssfCell.getBooleanCellValue());
		 } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			 String cellValue = "";
			 if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
				 Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
				 cellValue = sdf.format(date);
			 }else{
				 DecimalFormat df = new DecimalFormat("#.##");
				 cellValue = df.format(xssfCell.getNumericCellValue());
				 String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
				 if(strArr.equals("00")){
					 cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
				 }	
			 }
			 return cellValue;
		 } else {
			return String.valueOf(xssfCell.getStringCellValue());
		 }
	}	
/**
 * 自定義xssf日期工具類
 * @author lp
 *
 */
class XSSFDateUtil extends DateUtil{
	protected static int absoluteDay(Calendar cal, boolean use1904windowing) {  
        return DateUtil.absoluteDay(cal, use1904windowing);  
    } 
}</span></span>

2、ExcelRead:讀取Excel類

package com.ssm.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
 * 讀取Excel
 * @author lp
 *
 */
public class ExcelRead {	
	public int totalRows; //sheet中總行數
	public static int totalCells; //每一行總單元格數
	/**
	 * read the Excel .xlsx,.xls
	 * @param file jsp中的上傳檔案
	 * @return
	 * @throws IOException 
	 */
	public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
		if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
			return null;
		}else{
			String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
			if(!ExcelUtil.EMPTY.equals(postfix)){
				if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
					return readXls(file);
				}else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
					return readXlsx(file);
				}else{					
					return null;
				}
			}
		}
		return null;
	}
	/**
	 * read the Excel 2010 .xlsx
	 * @param file
	 * @param beanclazz
	 * @param titleExist
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("deprecation")
	public List<ArrayList<String>> readXlsx(MultipartFile file){
		List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
	    // IO流讀取檔案
	    InputStream input = null;
	    XSSFWorkbook wb = null;
	    ArrayList<String> rowList = null;
		try {
			input = file.getInputStream();
		    // 建立文件
		    wb = new XSSFWorkbook(input);           		    
	        //讀取sheet(頁)
	        for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
	        	XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
	        	if(xssfSheet == null){
	        		continue;
	        	}
	        	totalRows = xssfSheet.getLastRowNum();	        	
	        	//讀取Row,從第二行開始
	        	for(int rowNum = 1;rowNum <= totalRows;rowNum++){
	        		XSSFRow xssfRow = xssfSheet.getRow(rowNum);
	        		if(xssfRow!=null){
	        			rowList = new ArrayList<String>();
	        			totalCells = xssfRow.getLastCellNum();
	        			//讀取列,從第一列開始
	        			for(int c=0;c<=totalCells+1;c++){
	        				XSSFCell cell = xssfRow.getCell(c);
	        				if(cell==null){
	        					rowList.add(ExcelUtil.EMPTY);
	        					continue;
	        				}	        				
	        				rowList.add(ExcelUtil.getXValue(cell).trim());
	        			}	
					list.add(rowList);         				        			
	        		}
	        	}
	        }
	        return list;
		} catch (IOException e) {			
			e.printStackTrace();
		} finally{
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	/**
	 * read the Excel 2003-2007 .xls
	 * @param file
	 * @param beanclazz
	 * @param titleExist
	 * @return
	 * @throws IOException 
	 */
	public List<ArrayList<String>> readXls(MultipartFile file){ 
		List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
	    // IO流讀取檔案
	    InputStream input = null;
	    HSSFWorkbook wb = null;
	    ArrayList<String> rowList = null;
		try {
			input = file.getInputStream();
		    // 建立文件
		    wb = new HSSFWorkbook(input);           		    
	        //讀取sheet(頁)
	        for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
	        	HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
	        	if(hssfSheet == null){
	        		continue;
	        	}
	        	totalRows = hssfSheet.getLastRowNum();	        	
	        	//讀取Row,從第二行開始
	        	for(int rowNum = 1;rowNum <= totalRows;rowNum++){
	        		HSSFRow hssfRow = hssfSheet.getRow(rowNum);
	        		if(hssfRow!=null){
	        			rowList = new ArrayList<String>();
	        			totalCells = hssfRow.getLastCellNum();
	        			//讀取列,從第一列開始
	        			for(short c=0;c<=totalCells+1;c++){
	        				HSSFCell cell = hssfRow.getCell(c);
	        				if(cell==null){
	        					rowList.add(ExcelUtil.EMPTY);
	        					continue;
	        				}	        				
	        				rowList.add(ExcelUtil.getHValue(cell).trim());
	        			}	     
	        			list.add(rowList);
	        		}	        		
	        	}
	        }
	        return list;
		} catch (IOException e) {			
			e.printStackTrace();
		} finally{
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}


3、Controller
        /**
	 * 轉到Excel上傳頁面
	 * @return
	 * @author lp
	 */
	@RequestMapping(value="/read")
	public String addExcel(){
		return "baseInfo/testExcel";
	}
/**
	 * 讀取Excel資料到資料庫
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 * @author lp
	 */
	@RequestMapping(value="/readExcel")	
	public ModelAndView readExcel(@RequestParam(value="excelFile") MultipartFile file,HttpServletRequest request,HttpSession session) throws IOException{
		ModelAndView mv = new ModelAndView();
		//判斷檔案是否為空
		if(file == null){
			mv.addObject("msg", "failed");
			mv.setViewName("excel_result");
			return mv;
		}
                String name = file.getOriginalFilename();
		long size = file.getSize();
		if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){
			mv.addObject("msg", "failed");
			mv.setViewName("excel_result");
			return mv;
		}
		//讀取Excel資料到List中
		List<ArrayList<String>> list = new ExcelRead().readExcel(file);
                //list中存的就是excel中的資料,可以根據excel中每一列的值轉換成你所需要的值(從0開始),如:
		User user = null;
		List<User> liseUser = new ArrayList<User>();
		for(ArrayList<String> arr:list){						
			user= new User();						
			user.setAuthor(list.get(0));//每一行的第一個單元格
			listUser.add(user);
		}
		if(userService.saveBatchInsert(listUser)){
			mv.addObject("msg", "success");
		}else{
			mv.addObject("msg", "failed");
		}					
		mv.setViewName("excel_result");
		return mv;
	}</span></span>
4、jsp

(1)主頁面新增“Excel匯入”

<a href="javascript:addExcel();"><em>Excel匯入</em></a>function addExcel(){var dg = new $.dialog({title:'匯入Excel',id:'excel',width:1000,height:400,iconTitle:false,cover:true,maxBtn:false,xButton:true,resize:false,page:'user/read.html',});dg.ShowDialog();}

(2)匯入頁面
<body>
    <form action="readExcel.html" enctype="multipart/form-data" method="post" id="batchAdd" name="batchAdd" target="result" onsubmit="return check();>
        <div style="margin: 30px;">
        <div><input id="excel_file" type="file" name="excelFile" size="50"/>
    </form>
    <iframe name="result" id="result" src="about:blank" frameborder="0" width="0" height="0"></iframe>
</body>
</html>
<script type="text/javascript">
		var dg;
		$(document).ready(function(){			
			dg = frameElement.lhgDG;
			dg.addBtn('ok','儲存',function(){
			$("#batchAdd").submit();
			this.disabled=true;						
			});
		});
		
		function success(){
			if(dg.curWin.document.forms[0]){
				dg.curWin.document.forms[0].action = dg.curWin.location+"";
				dg.curWin.document.forms[0].submit();
			}else{
				dg.curWin.location.reload();
			}
			dg.cancel();
		}
		
		function failed(){
			alert("上傳失敗!");
		}
</script>
(3)提示頁面
<body>
	<script type="text/javascript">
		var msg = "${msg}";
		if(msg=="success" || msg==""){
			alert("儲存成功");
			parent.success();
		}else{
			parent.failed();
		}
	</script>
</body>
5、service層

service
boolean saveBatchInsert(List<User> listUser);

serviceimpl
@Transactional
public boolean saveBatchInsert(List<User> listUser){
    boolean flag = false;
    if(listUser!= null){
        userMapper.batchInsert(listUser);
        flag = true;
    }
    return flag;
}


6、dao層

void batchInsert(List<User> list);

7、xml(oracle) 
<insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="false" keyProperty="Id">
		insert into baseinfo(ID,Name,Sex,Birth,IdCardNo,Address,Tel,Author,AddDate,Status) 
		<foreach collection="list" item="item" index="index" separator="union all">
			(select
		<span style="white-space:pre">	</span>#{item.id,jdbcType=NUMERIC},
		       #{item.name,jdbcType=VARCHAR},
		       #{item.sex,jdbcType=CHAR},		       
		       #{item.birth,jdbcType=DATE},
		       #{item.idCardNo,jdbcType=CHAR},		      
		       #{item.address,jdbcType=VARCHAR},		       
		       #{item.tel,jdbcType=VARCHAR},		      
		       #{item.author,jdbcType=VARCHAR},
		       #{item.addDate,jdbcType=DATE},
		       #{item.status,jdbcType=CHAR}		       
		    from dual)
		</foreach>            
	</insert>