티스토리 뷰

 

목표

 

자바 엑셀 POI라이브러리를 사용해서 기존에 있던 엑셀파일에 데이터를 넣는 작업을 하였다.

 

input파일

위의 이미지는 기존 엑셀 서식이고

D5~D10 위치에 랜덤값의 데이터를 넣으면 평균값이 찍히게 하는것이 목표이다.

평균값을 계산하는 메서드는 사전에 엑셀 작업이 미리 되어있기 때문에 내가 굳이 설정할 필요는 없다.

내가 할 일은 랜덤 값을 넣어주기만 하면 된다.

 

 

 

문제1

 

평균값 제거하는 레코드가 제거됨

apache POI 3버전을 사용했을때

: 레코드가 제거되었고, 파일을 복원하라는 메세지가 떴다.

복원을 하면 위에처럼 데이터가 입력되고 평균값 계산하는 메서드는 없어져버렸다.

이유를 몰라 한참을 헤멨다,

버전이 잘못된줄 알고 POI 버전을 최신버전으로 올렸더니, 에러 메세지는 없어지고 데이터는 입력되었다. 

하지만 여전히 메서드는 동작하지 않았다...

 

 

 

getRow

 

xssfSheet.getRow(4).createCell(3).setCellValue((int)(Math.random()*100));

기존에 createRow를 이용해서 데이터를 넣어줬는데, getRow를 사용해야한다.

 

createRow(4)를 사용해서  5번째 행을 만들어줬는데,

그렇게 되면 평균값을 넣는행도 같은 5번째 열이여서 초기화되면서 메소드가 제거되어버린것.

따라서 getRow(4)를 이용해서 기존의 데이터를 가져와야한다.

 

getCell도 같은원리이다.

 

 

문제2

 

평균값 계산하는 메소드가 동작하지 않음

getRow를 사용하니까 메소드가 제거되지는 않았지만

이번에는 동작을 하지 않았다.. ㅠㅠ

 

 

 

setForceFormulaRecalculation

 

xworkbook.setForceFormulaRecalculation(true);

setForceFormulaRecalculation 메서드는 통합문서를 열 때 Excel에서 수식 값을 강제로 다시 계산하게 하는 메서드이다.

 

 

해결!

 

 

 

코드

 

전체코드

package excel_test.web;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.logging.log4j.core.tools.picocli.CommandLine.Help.TextTable.Cell;
import org.apache.poi.ss.format.CellFormatType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class randomExcelController {
	/*
	 * 엑셀에 랜덤함수 넣기 
	 */
	@RequestMapping(value = "/randomExcelFile.do")
	public void excel02() throws IOException{
			
			//엑셀 파일 경로
			String inputfileName = "C:\\input\\temp1.xlsx";
			String outputfileName = "C:\\output\\temp1.xlsx";
			
			//FileInputStream로 파일 읽어오기
			FileInputStream readfile = new FileInputStream(inputfileName);
			//Workbook 생성, xlsx 파일 read
			XSSFWorkbook xworkbook =  new XSSFWorkbook(readfile);
			//엑셀 파일의 시트
			XSSFSheet xssfSheet = xworkbook.getSheetAt(0);
			
			XSSFRow xssfRow = null;
			XSSFCell xssfCell = null;
			
			//엑셀에 데이터 입력하기
			xssfSheet.getRow(4).createCell(3).setCellValue((int)(Math.random()*100)); 
			xssfSheet.createRow(5).createCell(3).setCellValue((int)(Math.random()*100)); 
			xssfSheet.createRow(6).createCell(3).setCellValue((int)(Math.random()*100)); 
			xssfSheet.createRow(7).createCell(3).setCellValue((int)(Math.random()*100)); 
			xssfSheet.createRow(8).createCell(3).setCellValue((int)(Math.random()*100)); 
			xssfSheet.createRow(9).createCell(3).setCellValue((int)(Math.random()*100));
			
			xworkbook.setForceFormulaRecalculation(true);
			 
			//저장
			FileOutputStream makefile = new FileOutputStream(outputfileName);
			xworkbook.write(makefile);
			
			//종료
			readfile.close();			//FileInputStream
			makefile.close();			//FileOutputStream
			
	}
}

 

 

 

실행 전 후

 

       input               ---------------------------------------------------------------------->                  output

 

'JAVA' 카테고리의 다른 글

엑셀 다운로드 (AbstractXlsxView)  (0) 2022.09.08
POI를 이용해 엑셀 파일 수정하기  (0) 2022.06.15
API Server Test 01 | postman 사용  (0) 2022.06.03
예외처리란  (0) 2022.04.22
이클립스 자주쓰는 단축키  (0) 2022.04.04
댓글