opencsv 파일 읽기

3592 단어 Excel
/**
 * 
 * CSV 
 * 
 * Created on 2014-08-07
 * @author 
 * @reviewer 
 */
public class CsvUtils {

    /**
     * CSV 
     * @param head
     * @param dataList
     * @param outPutPath
     * @param filename
     * @return 
     * @return
     */
    public static  void createCSVFile( LinkedHashMap fieldMap,List list,
    		 HttpServletResponse response) {        
     //  : 
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();

        //  response 
        response.reset();
        response.setContentType("application/vnd.ms-excel"); //  excel 
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".csv");
        OutputStream out = null;
        try {
        	out=response.getOutputStream();
            List headList = new ArrayList();
            String[] enFields = new String[fieldMap.size()];
            int count = 0;
            for (Entry entry : fieldMap.entrySet()) {
            	headList.add(entry.getValue()) ;
            	enFields[count] = entry.getKey();
                count++;
            }
            writeRow(headList,list, out,enFields);

        } catch (Exception e) {
        	new BusinessException(" csv ");
        } finally {
        	try {
        		out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

	/**
     *  
     * @param 
     * @param row
     * @param csvWriter
     * @throws Exception 
     */
    private static  void writeRow(List headList,List row, OutputStream out,String[] enFields) throws Exception {
    	//  
    	StringBuffer head = new StringBuffer();
    	for (int i = 0; i < headList.size(); i++) {
    		Object data=headList.get(i);
    		head.append("\"").append(data);
    		if(i  
     * @return  bean 
     */
    public static  List getCsvData(InputStream inputStream, Class clazz) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(inputStream, "utf-8");
        } catch (Exception e) {
        	new BusinessException(" csv ");
        }
        
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);
        /*
            withSkipLines  
            withQuoteChar  
         */
        CsvToBean csvToBean = new CsvToBeanBuilder(in).withSkipLines(1)
                .withSeparator(',')
                .withQuoteChar('\"')
                .withType(clazz).build();
        return csvToBean.parse();
    }
}

좋은 웹페이지 즐겨찾기