使用 Tablesaw 處理 CSV

Java 中的資料匯入

Anthony Markham

VP Quant Developer

讀取 CSV 檔

  • 使用 read().csv() 讀取 CSV 檔
import tech.tablesaw.api.Table;
// Read in data
Table dataTable = Table.read().csv("data.csv");
  • 會自動偵測欄位型別,建立結構化的 Table 物件 💡
Java 中的資料匯入

CSV 讀取選項

  • 使用 CsvReadOptions 取得更細緻控制
import tech.tablesaw.io.csv.CsvReadOptions;
CsvReadOptions options = CsvReadOptions.builder("data.csv")

.separator(';') // Use semicolon as delimiter
.header(true) // First row contains headers
.missingValueIndicator("N/A") // Treat "N/A" as missing data
.build();
// Load the table using the custom options Table table = Table.read().csv(options);
Java 中的資料匯入

寫出 CSV 檔

  • 使用 write().csv() 進行基本匯出
  • 透過 Table 類別匯出
  • 保留欄位型別與結構
  • 自動處理特殊字元
// Write dataTable to output.csv
dataTable.write().csv("output.csv");
Java 中的資料匯入

CSV 寫出選項

  • 使用 CsvWriteOptions 指定寫出選項
CsvWriteOptions writeOptions = CsvWriteOptions
    .builder("output.csv")

.header(true) // Include column headers
.separator(';') // Use semicolon delimiter
.quoteAlways(true) // Quote all fields
.lineEnd("\r\n") // Windows-style line endings
.build();
// Write the CSV using the custom options
Table.write().csv(writeOptions);
Java 中的資料匯入

CSV 工作流程

  • 完整流程:read -> inspect -> process -> write
  • 非破壞式操作(會產生新檔) 📁
// Read CSV, modify, and write back
Table students = Table.read().csv("students.csv");

// View structure
System.out.println(students.structure());

// Save as new file
students.write().csv("students_processed.csv");
Java 中的資料匯入

一起來練習吧!

Java 中的資料匯入

Preparing Video For Download...