0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[スニペット]Java8 CSVの指定した列を加算して新たな列を作成して挿入

Posted at
import com.opencsv.*;
import java.io.*;
import java.util.*;

public class CSVSumWithInsertOpenCSV {
    public static void main(String[] args) throws IOException {
        String inputFile = "input.csv";
        String outputFile = "output.csv";

        // 加算対象の列名
        List<String> sumHeaders = Arrays.asList("Math", "Science", "English");
        String insertAfter = "English"; // この列の右に "Total" を挿入

        try (
            CSVReader reader = new CSVReader(new FileReader(inputFile));
            CSVWriter writer = new CSVWriter(new FileWriter(outputFile))
        ) {
            List<String[]> allRows = reader.readAll();
            if (allRows.isEmpty()) return;

            // ヘッダー取得
            String[] originalHeader = allRows.get(0);
            List<String> newHeader = new ArrayList<>(Arrays.asList(originalHeader));
            int insertIndex = newHeader.indexOf(insertAfter) + 1;
            newHeader.add(insertIndex, "Total");
            writer.writeNext(newHeader.toArray(new String[0]));

            // 各データ行の処理
            for (int i = 1; i < allRows.size(); i++) {
                String[] row = allRows.get(i);
                List<String> newRow = new ArrayList<>();

                // 合計の算出
                double sum = 0;
                Map<String, String> rowMap = new HashMap<>();
                for (int j = 0; j < originalHeader.length && j < row.length; j++) {
                    rowMap.put(originalHeader[j], row[j]);
                }

                for (String key : sumHeaders) {
                    try {
                        sum += Double.parseDouble(rowMap.getOrDefault(key, "0"));
                    } catch (NumberFormatException e) {
                        // 数値変換できない場合は 0 扱い
                        sum += 0;
                    }
                }

                // 新しい行を構築しながら "Total" を挿入
                for (int j = 0; j <= originalHeader.length; j++) {
                    if (j == insertIndex) {
                        newRow.add(String.valueOf(sum));
                    }
                    if (j < originalHeader.length) {
                        newRow.add(row[j]);
                    }
                }

                writer.writeNext(newRow.toArray(new String[0]));
            }
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?