opencsv 对文件的读写

/**
 * 
 * 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();
    }
}

 

你可能感兴趣的:(Excel)