All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gu.sql2java.excel.CSVReader Maven / Gradle / Ivy

There is a newer version: 5.2.0
Show newest version
package gu.sql2java.excel;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;

import gu.sql2java.excel.config.SheetConfig;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Strings.emptyToNull;

/**
 * CSV文件导入
 * @author guyadong
 * @since 3.29.0
 */
public class CSVReader  extends BaseExcelReader{
	

	public CSVReader() {
		super();
	}

	public CSVReader(Consumer beanConsumer) {
		super(beanConsumer);
	}

	public CSVReader(SheetConfig sheetConfig, Consumer beanConsumer) {
		super(sheetConfig, beanConsumer);
	}

	public CSVReader(SheetConfig sheetConfig, List rows, Consumer beanConsumer) {
		super(sheetConfig, rows, beanConsumer);
	}

	public CSVReader(SheetConfig sheetConfig) {
		super(sheetConfig);
	}
	@SuppressWarnings("rawtypes")
	public CSVReader(BaseExcelReader builder) {
		super(builder);
	}

	@Override
	public void read(InputStream inputStream, Charset charset, String format) throws IOException {
		if(null != format && !format.equalsIgnoreCase(".csv")) {
			throw new  IOException("UNSUPPORTED format :"+format);
		}
		try(CSVParser parser = new CSVParser(
				new InputStreamReader(inputStream,
						firstNonNull(charset, Charset.defaultCharset())), CSVFormat.DEFAULT)){
			Iterator itor = parser.iterator();
			read(itor);
			consumeRows();
		}
	}

	@Override
	protected String getCellAsString(CSVRecord row,int idx) {
		return null==row? null : emptyToNull(row.get(idx));
	}
	
	@Override
	protected boolean  isEmptyCell(CSVRecord row,int idx) {
		String cell = row.get(idx);
		return null== cell || cell.trim().isEmpty(); 
	}
	
	@Override
	protected List indexsOfRow(CSVRecord row){
		return null == row 
				? Collections.emptyList() 
				: ContiguousSet.create(Range.closedOpen(0, row.size()),	DiscreteDomain.integers()).asList();

	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy