struts2+poi和struts2+jxl实现读取EXCEL

今天花了半个小时,研究struts2通过第三方插件读取EXCEL功能,今贴出来,希望对网友们有用,默认的execute方法中,使用poi读取,read方法中使用jxl读取

package example;

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

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

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 com.opensymphony.xwork2.ActionSupport;


public class ExcelAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private File excel;
	
	public File getExcel() {
		return excel;
	}
	public void setExcel(File excel) {
		this.excel = excel;
	}
	@Override
	public String execute() throws Exception {
		try{
			InputStream is = new FileInputStream(excel);
			HSSFWorkbook work = new HSSFWorkbook(is);
			HSSFSheet sheet = work.getSheetAt(0);
			if(sheet != null){
				int rows = sheet.getPhysicalNumberOfRows();
				for(int i = 0;i < rows;i++){
					HSSFRow row = sheet.getRow(i);
					for(int j = 0;j<row.getPhysicalNumberOfCells();j++){
						HSSFCell cell = row.getCell(j);
						if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
							System.out.println("字符串:"+cell.getRichStringCellValue());
						}else if(HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()){
							System.out.println("数字:"+cell.getNumericCellValue());
						}
					}
				}
			}
			
			if(is != null){
				is.close();
			}
		}catch(Exception e){
			LOG.error("上传错误", e);
		}
		return SUCCESS;
	}

	public String read() throws Exception{
		Workbook wb = null;
        try {
        	InputStream is = new FileInputStream(excel);
            wb = Workbook.getWorkbook(is);
            Sheet[] sheets = wb.getSheets();    //获取工作 
            for(int i=0; i<sheets.length; i++) {
                Sheet sheet = sheets[i];
                for(int j=0; j<sheet.getRows(); j++) {
                    Cell[] cells = sheet.getRow(j);    //读取一列 
                    if(cells != null && cells.length > 0) {   
                        String[] dataCells = new String[cells.length];
                        for(int k=0; k<cells.length; k++) {
                            dataCells[k] = ""+cells[k].getContents();
                            System.out.println(cells[k].getContents());
                        }//column
                    }
                }//one sheet
            }//xls file
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {    
            e.printStackTrace();
        } finally {
            if(wb != null) {
                wb.close();
            }
        }

		return SUCCESS;
	}
	
}

相关推荐