Apache Spark多Sheet Excel写入:org.zuinnote库生成多文件而非单工作簿
解决Spark写入Excel单工作簿多Sheet的问题(针对org.zuinnote.spark.office.excel库)
我明白你遇到的困扰——用com.crealytics.spark.excel处理大文件失败后,切换到org.zuinnote.spark.office.excel却发现追加模式生成了两个独立文件,而不是同一个工作簿里的两个Sheet。其实这个库有专门的配置项来实现你要的效果,下面是具体的解决方案:
关键配置参数说明
这个库默认的追加行为是生成新文件,要让它在已有工作簿中新增Sheet,需要添加以下核心参数:
hadoopoffice.write.excel.createifnotexists: 设置为true,表示如果目标Excel文件不存在则创建,存在则在其中新增Sheethadoopoffice.write.excel.sheet.name: 指定当前DataFrame要写入的Sheet名称(避免使用默认名导致覆盖)- 确保两次写入使用完全相同的HDFS路径,且写入模式为
SaveMode.Append
修改后的代码示例
写入第一个Sheet(lines)
df3.coalesce(1).write() .format("org.zuinnote.spark.office.excel") .option("write.spark.defaultsheetname", "lines") .option("hadoopoffice.write.header.write", true) // 首次写入添加该参数,确保文件不存在时创建 .option("hadoopoffice.write.excel.createifnotexists", true) .save("hdfs://${namenode}/" + outFile + ".xls");
写入第二个Sheet(newlines)
fdf3.coalesce(1).write() .format("org.zuinnote.spark.office.excel") .option("hadoopoffice.write.header.write", true) // 指定要新增的Sheet名称 .option("hadoopoffice.write.excel.sheet.name", "newlines") // 允许在已有文件中新增Sheet .option("hadoopoffice.write.excel.createifnotexists", true) .mode(SaveMode.Append) .save("hdfs://${namenode}/" + outFile + ".xls");
额外注意事项
- coalesce(1)的性能考量:你用
coalesce(1)保证每个Sheet是单一文件,但处理1GB级数据时可能会给单节点带来压力。如果性能有问题,可以尝试结合库的hadoopoffice.write.excel.sheet.partitioning参数实现并行写入(前提是业务允许Sheet内数据分区存储)。 - 版本兼容性:建议使用
org.zuinnote.spark.office.excel0.1.0及以上版本,旧版本可能不支持新增Sheet的功能。 - HDFS权限检查:确认Spark进程拥有目标HDFS路径的读写权限,避免因权限问题导致写入失败。
这样修改后,两个DataFrame就会被写入同一个Excel工作簿的lines和newlines两个独立Sheet中了。
内容的提问来源于stack exchange,提问作者Arjun




