/**
* 파일 읽어오기
* */
FileInputStream fis=new FileInputStream("D:/excelTest/inputExcel.xls");
HSSFWorkbook workbook=new HSSFWorkbook(fis); // 읽어올 파일
List<Map> inputList = new ArrayList<>();
Map<String,String> inputMap;
Sheet sheet=workbook.getSheet("sheet1"); //파일에서 sheet1 가져오기
int rows=sheet.getPhysicalNumberOfRows(); // sheet1의 row 갯수 가져오기
for(int rowindex=1;rowindex<rows;rowindex++)
{
//행을읽는다
Row row=sheet.getRow(rowindex); //rowindex에 해당하는 row 값
if(row !=null)
{
Cell first=row.getCell(0); //해당 row의 첫번째 cell 가져오기
Cell second=row.getCell(1);
Cell third=row.getCell(2);
double firstString=first.getNumericCellValue(); //숫자인경우 value
String secondString=second.getStringCellValue();// 문자인 경우
String thirdString=third.getStringCellValue();
inputMap = new HashMap<>();
inputMap.put("first",firstString+"");
inputMap.put("second",secondString);
inputMap.put("third",thirdString);
inputList.add(inputMap);
}
}
/**
* 파일 저장 시키기
* */
Workbook outWorkbook = new HSSFWorkbook(); // 저장할 workbook
Sheet outSheet = outWorkbook.createSheet("sheet1"); // sheet 만들기
int count = 0;
int rowNo = 0;
Row headerRow = outSheet.createRow(rowNo++); //첫번째 row (0) 생성 후 rowNo 늘리기
// header 설정
headerRow.createCell(0).setCellValue("첫 번째"); //첫번째 header 설정
headerRow.createCell(1).setCellValue("두 번째");
headerRow.createCell(2).setCellValue("세 번째");
for(Map <String,String> m : inputList)
{
Row outRow = outSheet.createRow(rowNo++);
outRow.createCell(0).setCellValue(++count); //row 첫번째 cell 설정
outRow.createCell(1).setCellValue(m.get("first"));
outRow.createCell(2).setCellValue(m.get("second"));
outRow.createCell(3).setCellValue(m.get("third"));
}
try { //파일에 쓰기
File xls = new File("D:/excelTest/outExcel.xls");
FileOutputStream fileOutputStream = new FileOutputStream(xls);
outWorkbook.write(fileOutputStream); //outExcel.xls에 작성된 내용 쓰기
}catch(Exception e){
e.printStackTrace();
}
}