Export Csv

배세훈·2021년 8월 29일
0

java

목록 보기
6/16

CSV FILE 만들기

public File exportCsv(){
	
    File file = null;
    CSVWriter csvWriter = null;
    
    String fileName = "user.csv";
    file = new File(fileName);
    String encoding = "UTF-8";
    
    csvWriter = new CSVWriter(new FileWriterWithEncdoing(fileName, encoding, ',', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
    
    String ex1 = "hong,28,176cm,77kg";
    csvWriter.writeNext(ex1.split(",");
    csvWriter.writeNext(new String[1]);
    csvWriter.flush();
    
    if(csvWriter!=null){
    	try{
        	csvWriter.close();
        }catch(IOException e){
        	
        }
    }
    
    return file;
    
}

File Download

public void doDownload(HttpServletRequest request, HttpServletResponse response, File file) throws IOException{
	
    ServletContext context = request.getServletContext();
    FileInputStream inputStream = new FileInputStream(file);
    
    String mimeType = context.getMimeType(file.getAbsolutePath());
    
    if(mimeType == null){
    	mimeType = "application/ontet-stream";
    }
    
    response.setContentType(mimeType);
    response.setContentLength((int) file.length());
    
    String fileName = java.net.URLEncoder.encode(file.getName(), "utf-8").replacAll("\\+", "%20");
    String headerKey = "Content-Disposition";
    String headerKey = String.format("attachment; filename=\"%s\"", fileName);
    
    response.setHeader(headerKey, headerValue();
    
    OutputStream outStream = response.getOutputStream();
    
    if("text/csv".equalsIgnoreCase(mimeType)){
    	outStream.write(239);
        outStream.write(187);
        outStream.write(191);
    }
    
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    
    while((bytesRead = inputStream.read(buffer)) != -1){
    	outStream.write(buffer, 0, bytesRead);
    }
    
    inputStream.close();
    outStream.close();
    
}

Spring Boot를 통한 CSV Export & Download

1. gradle 설정
//build.gradle

plugins{
	id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.attacomsian'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories{
	mavenCentral()
}

dependencies{
	implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.opencsv:opencsv:4.5'
}
pom.xml
<dependency>
	<groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.5</version>
</dependency>
User Model
// User.java

import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvBindByPosition;

public class User{
	
    private long id;
    private String name;
    private String email;
    private String country;
    private int age;
    
    public User(long id, String name, String email, String country, int age){
    	this.id = id;
        this.name = name;
        this.email = email;
        this.country = country;
        this.age = age;
    }
    
    // getter, setter...
    
}
UserService.java
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService{
	public List<User> listUsers(){
    	List<User> users = new ArrayList<>();
        
        //create dummy users
        users.add(new User(1, "Jack Lee", "jack@example.com", "Germany", 35));
        users.add(new User(2, "Jovan Srovoki", "jovan@naver.com", "Russia", 21));
        users.add(new User(3, "Atta", "atta@gmail.com", "Pakistan", 29));
        
        return users;
    }
}
Generate & Download CSV File
// UserController.java

import com.attacomsian.exportcsv.data.User;
import com.attacomsian.exportcsv.data.UserService;
import com.opencsv.CSVWriter;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;

@Controller
public class UserController{
	private UserService userService;
    
    public UserController(UserService userService){
    	this.userService = userService;
    }
    
    @GetMapping("/export-users")
    public void exportCSV(HttpServletResponse response) throws Exception{
    	
        String filename = "users.csv";
        
        response.setContentType("text/csv");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
        
        // create a csv writer
        StatefulBeanToCsv(User> writer = new StatefulBeanToCsvBuilder<User>(response.getWriter())
        .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
        .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
        .withOrderedResults(false)
        .build();
     
     	// write all users to csv file
        writer.write(userService.listUsers());
    }
    
}

profile
성장형 인간

0개의 댓글