struts1 poi Excel批量导入支持xls和xlsx-源码java

jar包:

           

基本的poi导入后,如果要支持xlsx格式的excel要导入dom4j-1.6.1.jar、stax-api-1.0.1.jar、xmlbeans-2.3.0.jar

 所需要的源码下载地址:http://download.csdn.net/detail/myfmyfmyfmyf/6774399

 

package poi.excel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class ExcelPoiAction extends DispatchAction{

	
	public ActionForward upload(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ExcelPoizForm form =(ExcelPoizForm)actionForm;
		try {
			//提示消息
			String message="";
			Workbook workbook =this.createWorkBook(form.getFile().getInputStream(),form.getFile().getFileName());
			//读取第一个sheet
			Sheet sheet = workbook.getSheetAt(0);
			//读取数据,从第二行开始,第一列岗位名称,第二列岗位描述,第三列岗位编号
			for(int i=1; i<=sheet.getLastRowNum(); i++){ 
				Row row = sheet.getRow(i);  
				System.out.println(row.getCell(4));
				
			}
			request.setAttribute("msgresult", "上传完成!"+message);
		} catch (FileNotFoundException e) {
			request.setAttribute("msgresult", "导入失败!");
			System.out.println("导入失败");	
		} catch (IOException e) {
			request.setAttribute("msgresult", "导入失败!");
			System.out.println("导入失败");
		}catch(Exception e){
			request.setAttribute("msgresult", "导入失败!");
			System.out.println("导入失败");
		}
		finally{
			return mapping.findForward("success");
		}
		
	}

	
	/*  * 判断是xls文件还是xlsx文件  */
	public Workbook createWorkBook(InputStream is,String fileName) throws IOException{    
		if(fileName.toLowerCase().endsWith("xls")){ 
			return new HSSFWorkbook(is);  
			} 
		if(fileName.toLowerCase().endsWith("xlsx")){  
			return new XSSFWorkbook(is); 
			}    
		return null; 
		}
	
}


 

你可能感兴趣的:(struts1 poi Excel批量导入支持xls和xlsx-源码java)