opencsv方式讀取csv檔案,詳解,示例
阿新 • • 發佈:2019-01-02
1.opencsv官網:http://opencsv.sourceforge.net/
jar包:opencsv-2.3.jar
2.讀取CSV檔案
3.寫入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:
[email protected]">牧羊仒</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; } }
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: [email protected]">牧羊仒</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不要使用任何的引號來引資料,預設是雙引號“”
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();
}