1. 程式人生 > >POI技術處理Excel表 .xls ..xlsx兩種格式的匯入操作

POI技術處理Excel表 .xls ..xlsx兩種格式的匯入操作

一、說明

1、文章轉載自:http://blog.csdn.net/onepersontz/article/details/49891405

原文標題====SpringMvc+POI 處理Excel的匯入操作功能====

提到了ImportExcelUtil.java(Excel解析工具類)、UploadExcelControl.java (Spring控制器)、InfoVo.java(儲存Excel資料對應的物件)、main.jsp(前端程式碼)以及配置檔案web.xml、springmvc-servlet.xml(只做簡單配置)、applicationContext-base.xml等。
2、本文只提Controller層、ImportExcelUtil工具類兩部分,原文中這兩部分匯入功能可能會有一些小問題,具體可看原文網友評論。


3、我對原文匯入部分程式碼進行略微修改後,匯入功能已實際運用當中,沒發現問題。

二、功能程式碼


首先先感謝下原文博主,然後上程式碼!!!!!
1、Controller層 

// 單號資訊service
@Autowired
public OrderService orderService ;		//服務層改為自己的
	/**
	 * 一鍵上傳Excel表資訊
	 * 
	 * @author Justin
	 * 
	 */
	@RequestMapping("order_add.action")
	public @ResponseBody List<String> uploadadd(MultipartFile myFile, HttpServletResponse res) throws IOException {
		List<String> errorList = new ArrayList<String>();
		try {
			ImportExcelUtil util = new ImportExcelUtil();	
			 InputStream input = null;
			 List<List<Object>> lists = null;
			 if(myFile.isEmpty()) {
				 log.error("檔案不存在!");
			 }else {
				if (errorList.size() == 0) {
				 String fileName = myFile.getOriginalFilename();
				 input = myFile.getInputStream(); 
				 lists = util.getBankListByExcel(input, fileName);
				 input.close();
				 //迴圈將excel中的資料存入庫
				 for(int i=1; i<lists.size(); i++) {
					 List<Object> list = lists.get(i);
					 Order order= new Order();	//實體類,改為自己的
					 order.setOrderNumber(util.getFormat(String.valueOf(list.get(0))));
					 order.setAddress(util.getFormat(String.valueOf(list.get(1))));
					 order.setPhone(util.getFormat(String.valueOf(list.get(2))));
					 orderService.add(order);	 		 
				 }			 
			 }
		}
		} catch (Exception e) {
			errorList.add("匯入單號資料錯誤");
			e.printStackTrace();
			log.error("系統錯誤", e.fillInStackTrace());
		}
		return errorList;
	}

2、ImportExcelUtil工具類

package poi;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ImportExcel {
	private final static String Excel_2003 =".xls";//2003版本的excel
	private final static String Excel_2007 =".xlsx";//2007版本的excel
	
	public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
		List<List<Object>> list = null;
		//得到一個Excel工作薄
		Workbook work = this.getWorkbook(in, fileName);
		if(work==null) {
			throw new Exception("Excel工作薄為空");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;
	    
		list = new ArrayList<List<Object>>();
		//遍歷Excel中所有的sheet
		for(int i=0;i<work.getNumberOfSheets();i++) {
			//獲得Excel中sheet工作表單
			sheet = work.getSheetAt(i);
			if(sheet==null) {continue;}
			//遍歷當前sheet中所有的行
			//int total = sheet.getPhysicalNumberOfRows();//如果excel有格式,這種方式取值不準確
			int totalRow = sheet.getLastRowNum();
			for(int j=sheet.getFirstRowNum();j<totalRow;j++) {
				//獲取一行
				row = sheet.getRow(j);
				if(row!=null && !"".equals(row)) {
					//獲取第一個單元格的資料,判斷是否存在
					Cell firstCell = row.getCell(0);
					if(firstCell!=null) {
						 //遍歷一行中每一列
						List<Object> li = new ArrayList<Object>();
						//int totalColumn = row.getLastCellNum();
						for(int y=row.getFirstCellNum();y<row.getLastCellNum();y++) {
							//獲取每一格
							cell = row.getCell(y);
							String cellCal = this.getCellValue(cell)+"";
							li.add(cellCal);
						}
						list.add(li);
					}
				}
			}
		}
		in.close();
		return list;
	}
	
	
    public Workbook getWorkbook(InputStream in,String fileName) throws Exception {
    	Workbook work = null;
    	//獲取檔案型別xls或者xlsx
    	String fileType = fileName.substring(fileName.lastIndexOf("."));
    	if(Excel_2003.equals(fileType)) {
    		work = new HSSFWorkbook(in);//2003  版本的Excel
    	}else if(Excel_2007.equals(fileType)) {
    		work = new XSSFWorkbook(in);
    	}else {
    		throw new Exception("解析檔案格式有誤");
    	}
    	return work;
    }
    /**
     * 對錶格中的資料進行格式化
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
    	 Object value = null;
    	 DecimalFormat df1 = new DecimalFormat("0");//格式化number,string 字串
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//日期格式化
    	 DecimalFormat df2 = new DecimalFormat("0.00");//格式化數字
    	 if(cell!=null && !"".equals(cell)) {
    		 switch(cell.getCellType()) {
    		 case Cell.CELL_TYPE_STRING:
    			 value = cell.getRichStringCellValue().getString();
    			 break;
    		 case Cell.CELL_TYPE_NUMERIC:
    			 if("General".equals(cell.getCellStyle().getDataFormatString())) {
    				 value = df1.format(cell.getNumericCellValue());
    			 }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
    				 value = sdf.format(cell.getDateCellValue());
    			 }else if(HSSFDateUtil.isCellDateFormatted(cell)) {
    				  Date date = cell.getDateCellValue();
    				  value = sdf.format(date);
    			 }else {
    				 value = df2.format(cell.getNumericCellValue());
    			 }
    			 break;
    		 case Cell.CELL_TYPE_BOOLEAN:
    			  value = cell.getBooleanCellValue();
    			  break;
    		 case Cell.CELL_TYPE_BLANK:
    			  value="";
    			  break;
    		default:
    			 break;
    		 }
    	 }
    	 return value;
    }
}