opencsv方式读取csv文件,详解,示例

时间:2021-11-27 10:01:49

1.opencsv官网:http://opencsv.sourceforge.net/

   jar包:opencsv-2.3.jar

   下载地址:http://sourceforge.net/projects/opencsv/files/latest/download

2.读取CSV文件

package com.szaisino.common.opencsv;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import au.com.bytecode.opencsv.CSVReader;

/**
*
* <b>所属模块:</b>发票处理系统.公用模块<br/>
* <b>类名称:</b>ReadCSVFile<br/>
* <b>类描述:</b> 读取CSV文件 <br/>
* <b>版本:</b>V1.0<br/>
* <b>创建人:</b><a href="mailto:han_huayi@163.com">牧羊仒</a><br/>
* <b>创建时间:</b>2016年4月20日 下午5:09:27<br/>
*/
public class ReadCSVFile {

private static final String ADDRESS_FILE = "d:\\addresses.csv";

/**
*
* 读取csv中的内容
*
* @return
* @throws IOException
* @return List<String[]>
* @exception 异常描述
* @see
*/
public static List<String[]> readCSVFile(File file, int startRow, String characters) throws IOException{
List<String[]> strArrayList = new ArrayList<String[]>();

CSVReader reader = null;
if (",".equalsIgnoreCase(characters)){
reader = new CSVReader(new FileReader(file));
} else {
//带分隔符
reader = new CSVReader(new FileReader(file),characters.toCharArray()[0]);
}

String[] nextLine;
int i = 1;
while ((nextLine = reader.readNext()) != null) {
// System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");

if (i>=startRow)
strArrayList.add(nextLine);

i++;
}

return strArrayList;
}

/**
*
* 读取csv中的内容
* Map key:csvFileFirstRow csv文件,表头标题;
* key:csvFileContent csv文件,内容(除去表头内容)
*
* @param file csv文件对象
* @param startRow 开始行
* @param characters 分隔符
* @return
* @throws IOException
* @return Map<String,List<String[]>>
* @exception 异常描述
* @see
*/
public static Map<String, List<String[]>> readCSVFileWithMap(File file, int startRow, String characters) throws IOException{
List<String[]> csvFileFirstRowArrayList = new ArrayList<String[]>();
List<String[]> strArrayList = new ArrayList<String[]>();

CSVReader reader = null;
if (",".equalsIgnoreCase(characters)){
reader = new CSVReader(new FileReader(file));
} else {
//带分隔符
reader = new CSVReader(new FileReader(file),characters.toCharArray()[0]);
}

String[] nextLine;
int i = 1;
while ((nextLine = reader.readNext()) != null) {
// System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");

if (i>=startRow)
strArrayList.add(nextLine);
else
csvFileFirstRowArrayList.add(nextLine);

i++;
}

Map<String, List<String[]>> map = new HashMap<String, List<String[]>>();
map.put("csvFileFirstRow", csvFileFirstRowArrayList);
map.put("csvFileContent", strArrayList);
return map;
}


}


3.写入CSV文件

package com.szaisino.common.opencsv;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import au.com.bytecode.opencsv.CSVWriter;

/**
*
* <b>所属模块:</b>发票处理系统.公用模块<br/>
* <b>类名称:</b>WriteCSVFile<br/>
* <b>类描述:</b> 写入CSV文件 <br/>
* <b>版本:</b>V1.0<br/>
* <b>创建人:</b><a href="mailto:han_huayi@163.com">牧羊仒</a><br/>
* <b>创建时间:</b>2016年4月20日 下午5:14:30<br/>
*/
public class WriteCSVFile {

/**
*
* 向CSV写数据
*
* @param writeFilePath 文件路径
* @param strArrayList 文件内容
* @return void
* @throws IOException
* @exception 异常描述
* @see
*/
public static void writeCSVFile(String writeFilePath, List<String[]> strArrayList, String characters) throws IOException{
//判断文件是否存在,如果存在,先删除
File file = new File(writeFilePath);

if (file.exists())
file.delete();

CSVWriter writer = null;
// try {
if (",".equalsIgnoreCase(characters)){
//初始化CSVWriter
writer = new CSVWriter(new FileWriter(file));
} else{
//初始化CSVWriter,带分隔符
writer = new CSVWriter(new FileWriter(file),characters.toCharArray()[0]);
}
// } catch (IOException e) {
// e.printStackTrace();
// }

writer.writeAll(strArrayList);

// try {
writer.close();
//} catch (IOException e) {
//e.printStackTrace();
//}
}

/**
*
* 向CSV写数据
*
* @param writeFilePath
* @param strArrayList
* @param strArrayList
* @return void
* @throws IOException
* @exception 异常描述
* @see
*/
public static void writeCSVFile(String writeFilePath, List<String[]> csvFileFirstRowList, List<String[]> contentArrayList, String characters) throws IOException{

//处理反斜杠
if (!writeFilePath.endsWith("\\") && !writeFilePath.endsWith("/")){ //如果不是以\\结尾,则加上\\
writeFilePath = writeFilePath+"\\\\";
}
//文件名
String fileName = writeFilePath+new SimpleDateFormat("yyyyMMdd").format(new Date())+".csv"; //yyyyMMddHHmm

//判断文件是否存在,如果存在,先删除
File file = new File(fileName);

if (file.exists())
file.delete();

CSVWriter writer = null;
if (",".equalsIgnoreCase(characters)){
//初始化CSVWriter
writer = new CSVWriter(new FileWriter(file));
} else{
//初始化CSVWriter,带分隔符
writer = new CSVWriter(new FileWriter(file),characters.toCharArray()[0]);
}

//csv表头数据+表体数据
csvFileFirstRowList.addAll(contentArrayList);
writer.writeAll(csvFileFirstRowList);

//关闭流
writer.close();
}
}
导出的csv文件如下(默认是带双引号的):
"手机号码","姓名","订单号","发票代码","发票号","发票日期","发票金额"
"000000000","牧羊仒","0121342","030012111","13244","20170217","100"

CSVWriter 的构造函数有好几个,这里示例试用的是含有3个参数的构造,
第一个是指定Writer(不同情况下我们可能使用不同的writer),
第二个参数是分隔符通常是分号或者逗号
第三个参数即是告知CSVWriter不要使用任何的引号来引数据,默认是双引号“”

导出不带双引号的csv文件:

public static void writeCSVFile(String writeFilePath, List<String[]> csvFileFirstRowList, List<String[]> contentArrayList, String characters) throws IOException{

//处理反斜杠
if (!writeFilePath.endsWith("\\") && !writeFilePath.endsWith("/")){ //如果不是以\\结尾,则加上\\
writeFilePath = writeFilePath+"\\\\";
}
//文件名
String fileName = writeFilePath+new SimpleDateFormat("yyyyMMdd").format(new Date())+".csv"; //yyyyMMddHHmm

//判断文件是否存在,如果存在,先删除
File file = new File(fileName);

if (file.exists())
file.delete();
//初始化CSVWriter
CSVWriter writer = new CSVWriter(new FileWriter(file), ',', CSVWriter.NO_QUOTE_CHARACTER);


//csv表头数据+表体数据
csvFileFirstRowList.addAll(contentArrayList);
writer.writeAll(csvFileFirstRowList);

//关闭流
writer.close();
}