합리적 낙관주의자

csv 파일을 엑셀 파일로 변환하기 본문

이상이 아닌 현실 💼/Web 💻

csv 파일을 엑셀 파일로 변환하기

sroa.chin 2025. 4. 17. 16:17

SuccessFactors 에서 데이터 내보내기를 통해 다운 받아지는 파일이 csv 파일밖에 없고, 이 파일을 사용하기 위해선 excel 파일로 변환해야 한다.

개별 파일의 경우는 excel을 열어서 인코딩, 구분 기호 등을 바꿔 csv 파일을 열 수 있지만 다수의 파일일 경우 꽤나 번거롭고 작업하기 불편했다. 하여 여러개의 파일을 한번에 변환할 수 있는 파일을 만들어보았다. 

 

파일 생성 후 Export 기능을 통해 jar 파일을 만들었는데, 하나 간과한 사실.. PC에 Java가 설치되어 있지 않으면 jar 파일을 실행할 수 없다는 점ㅠㅠ 그래서 다른 방법이 있을까 찾아보다가 launch4j 프로그램으로 jar 파일을 exe 로 변환시켜줬다. 옵션인 jre 폴더와 함께 빌드하고, jar파일, exe파일, jre 파일을 함께 전달하면 Java 설치 안한 환경에서도 실행 가능하다! 

 

단점으로는 저 세개의 파일을 압축하자니 파일이 너무 무거워지는데., 이건 추후에 다른 방법 없는지 고민해보겠음...

 

JFileChooser  을 사용해 다중 파일 선택, csv 파일만 조회 등 기능 추가하여 파일 업로드 → OpenCsv 로 csv 파일을 읽은 뒤 →   Apache Poi 라이브러리로 excel 파일 생성 

package csv_to_excel_converter.csv_to_excel_converter;
import com.opencsv.CSVReader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

import java.io.*;


public class CsvToExcelConverter {
	
	public static void main(String[] args) {
        JFileChooser fileChooser = new JFileChooser();
        // 여러 파일 선택 허용
        fileChooser.setMultiSelectionEnabled(true);
        // csv 파일만 보이도록 필터 추가
        FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV 파일 (*.csv)", "csv");
        fileChooser.setFileFilter(filter);

        int returnValue = fileChooser.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File[] csvFiles = fileChooser.getSelectedFiles();
            if (csvFiles.length == 0) {
                // 파일이 하나만 선택된 경우 getSelectedFile()로 가져옴
                File singleFile = fileChooser.getSelectedFile();
                if (singleFile != null) {
                    csvFiles = new File[]{singleFile};
                }
            }
            int successCount = 0;
            for (File csvFile : csvFiles) {
                if (convertToExcel(csvFile.getAbsolutePath())) {
                    successCount++;
                }
            }
            JOptionPane.showMessageDialog(null, 
                String.format("총 %d개 파일 중 %d개 변환 완료★", csvFiles.length, successCount));
        }
    }


    private static boolean convertToExcel(String csvPath) {
        try (
            CSVReader reader = new CSVReader(
                new InputStreamReader(new FileInputStream(csvPath), "UTF-8")
            );
            Workbook workbook = new XSSFWorkbook()
        ) {
            Sheet sheet = workbook.createSheet("Sheet1");
            String[] nextLine;
            int rowNum = 0;
            while ((nextLine = reader.readNext()) != null) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < nextLine.length; i++) {
                    row.createCell(i).setCellValue(nextLine[i]);
                }
            }
            String excelPath = csvPath.replaceAll("(?i)\\.csv$", ".xlsx");
            try (FileOutputStream fos = new FileOutputStream(excelPath)) {
                workbook.write(fos);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

 

Java 파일에서 사용한 라이브러리는 pom.xml에 추가해주었다.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>csv-to-excel-converter</groupId>
  <artifactId>csv-to-excel-converter</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>csv-to-excel-converter</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- Apache POI -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
    <!-- OpenCSV -->
    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>5.7.1</version>
    </dependency>
  </dependencies>
 <build>
	  <plugins>
	  	<plugin>
		    <groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-assembly-plugin</artifactId>
		    <version>3.6.0</version>
		    <configuration>
		        <descriptorRefs>
		            <descriptorRef>jar-with-dependencies</descriptorRef>
		        </descriptorRefs>
		    </configuration>
		    <executions>
		        <execution>
		            <phase>package</phase>
		            <goals>
		                <goal>single</goal>
		            </goals>
		        </execution>
		    </executions>
		</plugin>
		
		<plugin>
		    <groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-jar-plugin</artifactId>
		    <configuration>
		        <archive>
		            <manifest>
		                <mainClass>Main</mainClass>
		                <addClasspath>true</addClasspath>
		                <addExtensions>true</addExtensions>
		            </manifest>
		        </archive>
		    </configuration>
		</plugin>
	</plugins>
 </build>
</project>