精华内容
下载资源
问答
  • opencsv解析csv文件

    千次阅读 2019-04-17 10:30:43
    * 解析csv文件并转成bean * @param file csv文件 * @param clazz 类 * @param <T> 泛型 * @return 泛型bean集合 */ public static <T> List<T> getCsvData(File file, Class<T> clazz) { try { ...

     

    注意如果是UTF-8-BOM模式,第一行会有bom的头标识,请修改文件编码模式为UTF-8,否则第一列会为空

    package com.ydd.tools;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import com.opencsv.CSVParser;
    import com.opencsv.bean.CsvToBean;
    import com.opencsv.bean.CsvToBeanBuilder;
    import com.opencsv.bean.HeaderColumnNameMappingStrategy;
    import com.ydd.model.Persion;
    
    /**
     * 	如果出现第一列读取不到的情况请修改编码模式为UTF-8, (UTF-8-BOM模式会丢失第一列)
     * @author pc1010
     */
    public class CsvUtil {
    
    	/**
    	 * 解析csv文件并转成bean
    	 * @param file  csv文件
    	 * @param clazz 类
    	 * @param <T>   泛型
    	 * @return 泛型bean集合
    	 */
    	public static <T> List<T> getCsvData(File file, Class<T> clazz) {
    		try {
    			List<T> result = new ArrayList<T>();
    			InputStream fileInput = new FileInputStream(file);
    			InputStreamReader in = new InputStreamReader(fileInput);
    			HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
    			strategy.setType(clazz);
    			CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in).withSeparator(CSVParser.DEFAULT_SEPARATOR).withThrowExceptions(false)
    					.withMappingStrategy(strategy).build();
    			Iterator<T> iterator = csvToBean.iterator();
    			while (iterator.hasNext()) {
    				try {
    					T t = iterator.next();
    					result.add(t);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    			return result;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    }
    

     

    展开全文
  • 1. 需要的依赖 <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --> <dependency> <groupId>com.opencsv<...opencsv</artifactId> <version>4.6</ver

    1. 需要的依赖

    <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
            <dependency>
                <groupId>com.opencsv</groupId>
                <artifactId>opencsv</artifactId>
                <version>4.6</version>
            </dependency>
    

    2. 编写csv解析工具

    import com.opencsv.bean.CsvToBean;
    import com.opencsv.bean.CsvToBeanBuilder;
    import com.opencsv.bean.HeaderColumnNameMappingStrategy;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.List;
    
    @Slf4j
    public class CsvUtils {
    
        public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) {
    
            InputStreamReader in = null;
            try {
                in = new InputStreamReader(file.getInputStream(), "UTF-8");  // UTF-8为解析时用的编码格式,csv文件也需要定义为UTF-8编码格式,解析格式根据csv文件的编码格式而定,csv默认编码格式为GBK
            } catch (IOException e) {
                log.error("读取csv文件失败! ---> " + e.getMessage());
            }
            HeaderColumnNameMappingStrategy<T> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
            mappingStrategy.setType(clazz);
            CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
                    .withSeparator(',')
                    .withIgnoreQuotations(true)
                    .withMappingStrategy(mappingStrategy)
                    .build();
            return csvToBean.parse();
    
        }
    
    }
    

    3. 调用csv工具类解析csv

    @RestController
    @Slf4j
    public class WarningForecastController {
    
        @PostMapping("/upload_caseinfo")
        public String upload(@RequestParam("file") MultipartFile file,
                             @RequestParam("info") String info) {
    
            System.out.println(info);
    		
            List<Test> csvData = CsvUtils.getCsvData(file, Test.class);
    
            csvData.forEach(s -> System.out.println(s.toString()));
            return null;
        }
    }
    
    展开全文
  • I have following csv file,"id","Description","vale"1,New"Account","val1"I am unable to read the above csv file with opencsv jar. It cannot read New"Account, since the double quotes inside data. My csv...

    I have following csv file,

    "id","Description","vale"

    1,New"Account","val1"

    I am unable to read the above csv file with opencsv jar. It cannot read New"Account, since the double quotes inside data. My csv reader constructor is following,

    csvReader = new CSVReader(new FileReader(currentFile), ',', '\"', '\0');

    解决方案

    That is as designed. Your constructor specifies a quote character as "\"" so OpenCSV will treat that character as a quote character, i.e. when it reads a quote it will ignore all commas until a matching quote is found.

    To get around this you could use a FilterReader.

    Reader reader = new FilterReader(fileReader) {

    private int filter(int ch) {

    return ch == '"'?' ':ch;

    }

    @Override

    public int read(char[] cbuf, int off, int len) throws IOException {

    int red = super.read(cbuf, off, len);

    for ( int i = off; i < off + red; i++) {

    cbuf[i] = (char)filter(cbuf[i]);

    }

    return red;

    }

    @Override

    public int read() throws IOException {

    return filter(super.read());

    }

    };

    展开全文
  • opencsv解析CSV

    2019-12-23 18:19:38
    opencsv 5.0 项目地址 http://opencsv.sourceforge.net maven坐标 <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.0</...

    前言

    • opencsv 5.0

    项目地址

    http://opencsv.sourceforge.net

    maven坐标

    <dependency>
    	<groupId>com.opencsv</groupId>
    	<artifactId>opencsv</artifactId>
    	<version>5.0</version>
    </dependency>
    

    用法

    csv文件内容示例:

    "48480","10","SCR,6-32X1/4',HX,TF,ZPS,TRI-PT","N7",""
    "DTHG6","10","null","Z6-9",""
    "1213C","11","SCR,6-32X1/4',FLH,MS,ZPS,CTSK","N4",""
    "N6370","15","TOOL,SYRNG,THRMGRS,V2","H4",""
    

    代码如下:

    final CSVParser parser = new CSVParserBuilder().withSeparator(',').withIgnoreQuotations(false).build();
    try (CSVReader csvReader = new CSVReaderBuilder(new FileReader("yourfile.csv")))
    				.withSkipLines(1)
    				.withCSVParser(parser)
    				.build()){
    	Iterator<String[]> iterator = csvReader.iterator();
    	while (iterator.hasNext()) {
    		String[] cols = iterator.next();
    		this.log.debug(StringUtils.join(cols, "|"));
    	}
    } catch (Exception e) {
    	this.log.error("parser error", e);
    }
    

    输出:

    48480|10|SCR,6-32X1/4',HX,TF,ZPS,TRI-PT|N7| 
    DTHG6|10|null|Z6-9| 
    1213C|11|SCR,6-32X1/4',FLH,MS,ZPS,CTSK|N4| 
    N6370|15|TOOL,SYRNG,THRMGRS,V2|H4| 
    
    展开全文
  • openCSV 开源程序解析CSV文件 2011年09月01日  读CSV  package au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. Licensed under the Apache License, Version 2.0 (the "License")...
  • 在使用opencsv这个jar包解析csv文件中,经常会碰到读取中文乱码的情况,这样其实有一种简单的办法,如下: String filePath = "F:/test.csv" ; File file = new File(filePath); CSVReader csvReader = null ...
  • C:\SystemUser\UniEAP V3.3.0\workspace\zzbx\EAPDomain\WEB-INF\lib 以上路径解析后,会变成:C:SystemUserUniEAP V3.3.0workspacezzbxEAPDomainWEB-INFlib,远非我们所要的结果。 处理方式:重构openCSV.jar里的...
  • OpenCSV

    2019-06-13 20:51:01
    OpenCSV地址:http://opencsv.sourceforge.net/ 使用示例(kotlin) ... * 导入excel并解析返回数据 */ override fun import(file: MultipartFile, sendType: String): ImportExcelDataVO? { try { ...
  • opencsv-2.3.jar解决有中文内容的CSV文件时,代码读取时乱码。 解决方案如下:重构opencsv-2.3.jar包里的CSVReader文件。 方法: public CSVReader(Reader paramReader, char paramChar1, char paramChar2, ...
  • 为了批量导入数据,采用了csv文件存储数据,后端写csv解析工具对数据进行读取和解析并导入数据库。(使用opencsv) pom依赖: <!-- csv文件解析依赖 --> <dependency> <groupId>com.opencsv<...
  • opencsv

    2016-08-19 14:54:00
    opencsv一个简单的CSV解析Java包。它封装了CSV格式文件的输出和读入,可以自动处理CSV格式中的特殊字符。 示例 File tempFile =  new  File("./Group" + querytime + ".csv");  OutputStreamWriter ...
  • OpenCsv使用

    2020-09-19 12:03:09
    OpenCsv是一个非常简单的CSV解析库,帮助我们更好处理CSV格式文件。 <!-- 使用opencsv --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId>...
  • 原始需求 使用定时任务,将用户的行为日志数据文件(.csv)解析为java对象,并批量落入clickhouse数据库(MySQL亦同理)。 行为日志包含:网站访问日志、...openCSV解析.csv映射为java对象 spring的定时任务@Scheduled
  • private static String splitResult(String once) { String result = ""; for (int i = 0; i < once.length(); i++) { if (once.charAt(i) != '"'... }
  • 尘封已久,再次开写。 为了回报社会,促进中国软件行业的发展。...解析pdf,可以用itext, pdfbox,然而这2个解析pdf表格却不行。 不能一行一行的解析。 要解析pdf的表格,还是得用tabula-java。 用tabula-ja...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 430
精华内容 172
关键字:

opencsv解析