opencsv
http://opencsv.sourceforge.net/
示例代码:
http://opencsv.sourceforge.net/
示例代码:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class ProcessCSV {
private static final String ADDRESS_FILE="D://examples/addresses.csv";
public static void main(String[] args) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(ADDRESS_FILE));
List<String[]> allElements = new ArrayList<String[]>();
allElements.add(new String[]{"张三","地址1","邮箱1"});
allElements.add(new String[]{"李四","地址2","邮箱2"});
writer.writeAll(allElements);
writer.close();
System.out.println("\nGenerated CSV File:" + ADDRESS_FILE);
CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
System.out.println("Name: ["+nextLine[0]+"]\nAddress: ["+nextLine[1]+"]\nEmail: ["+nextLine[2]+"]");
}
}
}
=======================================================
javacsv.jar下载地址:
http://sourceforge.net/project/showfiles.php?group_id=33066
public void readeCsv(){
try {
ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据
String csvFilePath = "c:/test.csv";
CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("SJIS")); //一般用这编码读就可以了
reader.readHeaders(); // 跳过表头 如果需要表头的话,不要写这句。
while(reader.readRecord()){ //逐行读入除表头的数据
csvList.add(reader.getValues());
}
reader.close();
for(int row=0;row<csvList.size();row++){
String cell = csvList.get(row)[0]; //取得第row行第0列的数据
System.out.println(cell);
}
}catch(Exception ex){
System.out.println(ex);
}
}
/**
* 写入CSV文件
*/
public void writeCsv(){
try {
String csvFilePath = "c:/test.csv";
CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));
String[] contents = {"aaaaa","bbbbb","cccccc","ddddddddd"};
wr.writeRecord(contents);
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}