struts2導入excel

  當前用於 通過java操作excel表格的工具類庫 這一目的手段有兩種:

1 jxl,一位日本程序員的開源類庫。缺點是不能夠支持Office 2003以上版本,對圖片識別和處理能力僅限於PNG格式。

2 POI, Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。功能強悍、性能穩定。相對與jxl來講,幾乎佔盡各方面優勢。 


採用poi的方法:

1,導入jar包,製作excel表格

poi-3.7


3,jsp上傳excel,java並獲得

<form id="empForm" >
		       <input type="file" id="excelPath" name="excelPath"/>  
			   <input type="button"  value="導入Excel" οnclick="importEmp()"/> 
		   </form> 
js判斷文件類型

 <script language="javascript">  
  //Excel文件導入到數據庫中  
function importEmp(){  
    //檢驗導入的文件是否爲Excel文件  
    var excelPath = document.getElementById("excelPath").value;  
    if(excelPath == null || excelPath == ''){  
        alert("請選擇要上傳的Excel文件");  
        return;  
    }else{  
        var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();   
        if(fileExtend == '.xls'){  
        }else{  
            alert("文件格式需爲'.xls'格式");  
            return;  
        }  
    }  
    //提交表單  
   document.getElementById("empForm").action="<%=request.getContextPath()%>/importStus";    
   document.getElementById("empForm").submit();  
}  
</script>  
struts.xml文件

<package name="tableInsert" extends="struts-default">  
        <action name="importStus" class="infoManage.action.tabInsertAction" method="tableInsert">  
            <result name="success">/JSP/Management/_tabInsert.jsp</result> 
            <result name="error">/JSP/Management/_tabInsert.jsp</result>  
        </action>  
     </package>  
    
java文件獲得:

//從頁面接收參數:文件的路徑  
	HttpServletRequest request = ServletActionContext.getRequest ();
         String excelPath = request.getParameter("excelPath");  
         System.out.print("excel路徑"+excelPath);
        //輸入流  
        InputStream fis = new FileInputStream("C:/Users/Administrator/Desktop/"+excelPath);
3,將獲得的excel文件解析

 //POI:得到解析Excel的實體集合  
        List<student> infos = ImportEmployee.importEmployeeByPoi(fis);  

package infoManage.action;
import java.io.File;  


import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;  
import java.util.Iterator;  
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.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 com.boxun.bean.ExcelWorkSheet;  
//import com.boxun.bean.Userinfo;  
//import com.boxun.biz.IUserBiz;  

import bean.student;

import com.opensymphony.xwork2.ActionSupport;  


public class ImportEmployee {

	/** 
	 * POI:解析Excel文件中的數據並把每行數據封裝成一個實體 
	 * @param fis 文件輸入流 
	 * @return List<EmployeeInfo> Excel中數據封裝實體的集合 
	 */  
	
	public static List<student> importEmployeeByPoi(InputStream fis) {  
	    //這裏是解析出來的Excel的數據存放的List集合  
	    List<student> infos = new ArrayList<student>();  //這裏是解析出來的Excel中的每一條數據封裝的實體BEAN.  
	    student student = null;  
	      
	    try {  
	        //創建Excel工作薄  
	        HSSFWorkbook hwb = new HSSFWorkbook(fis);  
	        //得到第一個工作表  
	        HSSFSheet sheet = hwb.getSheetAt(0);  
	        HSSFRow row = null;  
	        //日期格式化  
	        DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");  
	        //遍歷該表格中所有的工作表,i表示工作表的數量 getNumberOfSheets表示工作表的總數 
	        System.out.print( hwb.getNumberOfSheets()+"列數"+sheet.getPhysicalNumberOfRows());
	        
	        for(int i = 0; i < hwb.getNumberOfSheets(); i++) {  
	            sheet = hwb.getSheetAt(i);  
	            //遍歷該行所有的行,j表示行數 getPhysicalNumberOfRows行的總數  
	            for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {  
	                row = sheet.getRow(j);  
	                student = new student();  
	                  
	                //此方法調用getCellValue(HSSFCell cell)對解析出來的數據進行判斷,並做相應的處理  
//	                if(tabInsertAction.getCellValue(row.getCell(0)) != null && !"".equals(tabInsertAction.getCellValue(row.getCell(0)))) {  
//	                    student.setOrgId(Long.valueOf(tabInsertAction.getCellValue(row.getCell(0)))); 
	                    student.setStudentId(ImportEmployee.getCellValue(row.getCell(0)));
	                    System.out.print("學生學號"+ImportEmployee.getCellValue(row.getCell(0)));
	                    student.setStudentName(ImportEmployee.getCellValue(row.getCell(1)));
	                    student.setDeptId(ImportEmployee.getCellValue(row.getCell(2)));
	                    student.setClassId(ImportEmployee.getCellValue(row.getCell(3)));
	                    student.setPassword(ImportEmployee.getCellValue(row.getCell(4)));
	                    
//	                }  
//	                student.setEmployeeNumber(tabInsertAction.getCellValue(row.getCell(1)));  
//	                student.setFullName(tabInsertAction.getCellValue(row.getCell(2)));  
//	                student.setSex(tabInsertAction.getCellValue(row.getCell(3)));  
//	                if(tabInsertAction.getCellValue(row.getCell(4)) != null && !"".equals(tabInsertAction.getCellValue(row.getCell(4)))) {  
//	                    try {  
//	                        student.setDateOfBirth(ft.parse(tabInsertAction.getCellValue(row.getCell(4))));  
//	                    } catch (ParseException e) {  
//	                        e.printStackTrace();  
//	                    }  
//	                    student.setTownOfBirth(tabInsertAction.getCellValue(row.getCell(5)));  
//	                }  
//	                student.setNationalIdentifier(tabInsertAction.getCellValue(row.getCell(6)));  
	                infos.add(student);  
	            }  
	              
	        }  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    }  
	    return infos;  
	}  

	//判斷從Excel文件中解析出來數據的格式  
    private static String getCellValue(HSSFCell cell){  
        String value = null;  
        //簡單的查檢列類型  
        switch(cell.getCellType())  
        {  
            case HSSFCell.CELL_TYPE_STRING://字符串  
                value = cell.getRichStringCellValue().getString();  
                break;  
            case HSSFCell.CELL_TYPE_NUMERIC://數字  
                long dd = (long)cell.getNumericCellValue();  
                value = dd+"";  
                break;  
            case HSSFCell.CELL_TYPE_BLANK:  
                value = "";  
                break;     
            case HSSFCell.CELL_TYPE_FORMULA:  
                value = String.valueOf(cell.getCellFormula());  
                break;  
            case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值  
                value = String.valueOf(cell.getBooleanCellValue());  
                break;  
            case HSSFCell.CELL_TYPE_ERROR:  
                value = String.valueOf(cell.getErrorCellValue());  
                break;  
            default:  
                break;  
        }  
        return value;  
    }  
	        
}
此時,excel文件裏的數據就解析成了bean數據存在info中

4,遍歷info,將數據存入數據庫。

 //遍歷解析Excel的實體集合  
        for(student info:infos) {  
            //判斷學號是否存在(存在:做修改操作;不存在:做新增操作) 
           boolean state=tabInsertdao.selectEmpByEmpNum(info.getStudentId());  //判斷學生是否存在
           String state1=null;
            if(state == true) {       //該學生存在,修改操作
            	state1=tabInsertdao.UpdateStu(info);
            }else{                    //該學生不存在,添加操作
            	state1=tabInsertdao.addStu(info);
            }  
            setInfoString(state1);
        }  
        //關閉流  
        fis.close();  
        
		return SUCCESS;

有問題QQ:617238902聯繫





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