struts 2+poiとstruts 2+jxlによるEXCEL読み出しを実現
今日30分かかって、struts 2がサードパーティのプラグインを通じて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;
}
}