輸出具格式的 CSV 檔案
在清理完資料之後,你需要將其匯出給不同的使用單位。分析團隊需要標準的 CSV,歐洲系統預期使用分號作為分隔符,而舊式大型主機則要求沒有標頭的檔案。具備彈性的匯出選項,能確保你的資料可順利整合到多元的技術環境中。
Table 和 CsvWriteOptions 類別已為你匯入。
本練習屬於課程
Java 中的資料匯入
練習說明
- 將資料表寫出為標準 CSV。
- 以分號作為分隔符寫出。
- 為相容舊系統,寫出時不包含標頭列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class WriteCSVFiles {
public static void main(String[] args) {
try {
Table employeePerformance = Table.read().csv("employee_performance.csv");
System.out.println("Original data structure:");
System.out.println(employeePerformance.structure());
System.out.println("First 3 rows:");
System.out.println(employeePerformance.first(3));
// Write the table as a standard CSV
employeePerformance.____.csv("employee_performance_standard.csv");
// Write with a semicolon separator
employeePerformance.write().csv(CsvWriteOptions
.____("employee_performance_semicolon.csv")
.____(';')
.build());
// Write without headers for a legacy system
employeePerformance.write().csv(CsvWriteOptions
.builder("employee_performance_noheader.csv")
.____(____)
.build());
System.out.println("\nFiles successfully written to output directory.");
Table readBack = Table.read().csv("employee_performance_standard.csv");
System.out.println("\nVerification - Reading back semicolon-separated file:");
System.out.println(readBack.first(3));
} catch (Exception e) {
System.err.println("Error processing CSV files: " + e.getMessage());
}
}
}