csv增加一列
csv增加一列
package com.vfsd; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.csvreader.CsvReader; import com.csvreader.CsvWriter; public class CSVAddID { public static void main(String[] args) throws IOException { String inputCsvFileName1 = "F:\\PythonProject\\DoWhy_Project\\dowhy_202204\\data\\week_1.csv"; //String inputCsvFileName2 = "F:\\PythonProject\\DoWhy_Project\\dowhy_202204\\data\\week_75_6.csv"; String outputCsvFileName = "F:\\PythonProject\\DoWhy_Project\\dowhy_202204\\data\\week_1_13.csv"; readCSVAndWrite(inputCsvFileName1,outputCsvFileName); } /** * 读取CSV文件内容 * @param csvFileName * @throws IOException */ public static void readCSVAndWrite( String inputCsvFileName1, String outputCsvFileName) throws IOException{ try { // 创建CSV读对象 CsvReader csvReader1 = new CsvReader(inputCsvFileName1); //CsvReader csvReader2 = new CsvReader(inputCsvFileName2); // 读表头 csvReader1.readHeaders(); //csvReader2.readHeaders(); CsvWriter csvWriter1 = new CsvWriter(outputCsvFileName,',', Charset.forName("UTF-8")); String[] headers2 = {"id","XW1","XW2","XW3","XW4","XW5","XW6","XW7","XW8","GXW1","GXW2","GXW3","GXW4","GXW5","GXW6","GXW7","GXW8","GXW9","GXW10","GXW11","GXW12","GXW13"}; csvWriter1.writeRecord(headers2); //csvReader1.readRecord(); int n=1; while (csvReader1.readRecord()){ //System.out.println(csvReader1.getRawRecord()); //System.out.println(csvReader1.getRawRecord()); //for(int k=0;k<list_headers.size();k++) { // String indexHeader = list_headers.get(k); // String cell_value_str = csvReader.get(indexHeader); // cell_value = cell_value+Double.parseDouble(cell_value_str); //} String[] content2 = new String[headers2.length]; content2[0] = n+""; for(int k=1;k<headers2.length;k++) { String indexHeader = headers2[k]; String cell1_value_str = csvReader1.get(indexHeader); content2[k] = cell1_value_str; } csvWriter1.writeRecord(content2); // 读一整行 //System.out.println(csvReader.getRawRecord()); // 读这行的某一列 //System.out.println(csvReader.get("A")+"\t"+csvReader.get("B")+"\t"+csvReader.get("C")); n++; } csvWriter1.flush(); csvWriter1.close(); csvReader1.close(); } catch (IOException e) { e.printStackTrace(); }finally { System.out.println("finish..."); } } }
#########################
QQ 3087438119