写出带格式的 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());
}
}
}