본문 바로가기
Programming/java

업로드한 엑셀 파일 데이터 읽어오기

by 막이 2012. 9. 20.

지극히 개인적인 소스- ㅅ-.....

Struts1 을 사용했는데 formfile이 file 로 형변환이 되지 않았따 ㅠㅠㅠㅠㅠ

불러온 파일 데이터를 다시 읽어와서 file 객체로

저장한담에  excel 데이터를 읽어와따..

 

에러
Corrupt form data: premature ending
이유:
스트럿츠에서 멀티파트를 알아서 처리해줘요
그런데 POI로 작업하려는 상황에서 멀티파트로 리퀘스트를 다시 처리하려고 하면 이미 한번 파싱된 리퀘스트를 또 처리하려고 해서 나는 에러니까
FormFile 객체는 스트럿츠에서 지원해주는 거고
File은 java 에서 기본적으로 지원해주는거니까

 

public static List<?> readExcel(String type, FormFile uploadFile,

String path)

{

List<?> newList = null;

ArrayList<String> temp = new ArrayList<String>();

int cn = 0;

InputStream is = null;

FileInputStream fis = null;

byte[] fileBArray = null;

String fullname = path + "\\" + uploadFile.getFileName();

try

{

fileBArray = uploadFile.getFileData();

fis = new FileInputStream(new File(fullname));

fis.read(fileBArray);

is = fis;

}

catch (Exception e)

{

String error = "Cannot get input stram";

temp.add(error);

return temp;

}

try

{

Workbook wb = null;

try

{

wb = WorkbookFactory.create(fis);

}

catch (Exception e1)

{

try

{

// I have tried fis and is as well and I still throw an exception

wb = new XSSFWorkbook(fullname);

}

catch (Exception e2)

{

// doesn't even make it here - it throws an exception but is never caught

try

{

wb = new HSSFWorkbook(is);

}

catch (Exception e3)

{

String error = "problem with workbook: "

+ e3.getMessage();

temp.add(error);

return temp;

}

}

}

}

}

 

------------------------------------------------------

방법2.

//엑셀 파일 insert
 public void insertExcel(ActionForm form, HttpServletRequest request) throws Exception{
  
  SampleForm f=(SampleForm)form;
  FormFile formFile= f.getExcel_file();
  f.setAttach_idx("");
        f.setUse_yn("Y");
  try{
   
    DBHandler dbh = dao.startTransaction();
    String attach_idx = UploadHandler.newAttachIdx();

    //UploadHandler.upload(dbh, attach_idx, formFile, ServerConfig.getPath(Constants.ROOT_UP_PATH)+ "/hejExcel/", 0);
    String real_nm = FileUtil.upload(formFile, ServerConfig.getPath(Constants.ROOT_UP_PATH)+ "/hejExcel/", 0);
    //f.setAttach_idx(attach_idx);
    //String filePath =dao.getStringValue(getQuery("hejBbs.getFileName"), f);
    //System.out.println(filePath);
    InputStream inp = new FileInputStream(ServerConfig.getPath(Constants.ROOT_UP_PATH)+ "/hejExcel/"+real_nm);
    
    
    HSSFWorkbook wb = new HSSFWorkbook(inp);
    
    
    HSSFSheet sheet=wb.getSheetAt(0); //시트 가져오기
    int rows=sheet.getPhysicalNumberOfRows(); //Row 갯수 가져오기
    int cells=sheet.getRow(0).getPhysicalNumberOfCells(); //cell 갯수 가져오기
    System.out.println("열 갯수" + rows);
    System.out.println("cell 갯수 " + cells);
    if ( rows >= 2 ) { //1번째 줄일 제목 줄이기 때문에 2번부터 시작
        for(int i=1; i<rows; i++){ //row 루프
            HSSFRow row=sheet.getRow(i); //row 가져오기
            if(row != null && !"".equals(row.getCell((short) 0).getStringCellValue())){
                int idx=1;
                for(int c=0; c<cells;   c++){ //cell 루프
                    HSSFCell cell = row.getCell((short) c); //cell 가져오기
                    String value = "";

                    if(cell!=null){
                        switch(cell.getCellType()){ //cell 타입에 따른 데이타 저장
                            case HSSFCell.CELL_TYPE_FORMULA:
                                value=cell.getCellFormula();
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                             value= ""+cell.getNumericCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                value=""+cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                //value=""+cell.getBooleanCellValue();
                                value="";
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value=""+cell.getErrorCellValue();
                                break;
                            default:
                        }
                       
                        switch(c){
                       
                         //제목
                         case 0 :System.out.println("제목"+value);
                           f.setSample_title(value);
                           break;
                         //내용
                         case 1 :System.out.println("내용"+value);
                           f.setSample_contents(value);
                           break;
                         //REG_ID
                         case 2 :System.out.println("REG ID"+value);
                           f.setSabun(value);
                           String user_Id =dao.getStringValue(getQuery("hejBbs.getUserId"), f);
                           f.setReg_id(user_Id);
                           break;
                        }
                        //System.out.println("cell:"+cell.getCellNum()+", value:"+value);
                    }

                }
               
                dao.executeUpdate(getQuery("hejBbs.insert"), f);
                System.out.println("-------------------------------------------");
               
                dao.commit();
            }
        }
    }


      //dao.commit();
   }catch(Exception e){
   
   
   dao.rollback();
   throw e; 
  }finally{
   dao.endTransaction();
  }
 
}