xlsx - 使用pyspark读取到spark数据框时列映射错误

0 投票
1 回答
55 浏览
提问于 2025-04-13 16:34

我正在尝试使用下面的pyspark代码来读取Excel文件。

df_data = spark.read.format("com.crealytics.spark.excel") \
            .option("header", "true") \
            .option("dataAddress", f"'{sheet_name}'!A1") \
            .option("treatEmptyValuesAsNulls", "false")\
            .schema(custom_schema) \
            .load(file_path)

但是,列名的对应关系和文件中的顺序不一致。比如说:

file:
col1 col2 col3
12    23   null

Df output: 
  col2 col3 col1
  null 12    23

请告诉我如何解决这个列映射的排序问题。提前谢谢你。

1 个回答

0

我尝试了下面的方法:

from pyspark.sql.types import StringType, StructField, StructType
file_path = "/FileStore/tables/exclk.xlsx"
sheet_name = "Sheet1" 
schema = StructType([
    StructField("col1", StringType(), nullable=True),
    StructField("col2", StringType(), nullable=True),
    StructField("col3", StringType(), nullable=True)
])
desired_order = ['col1', 'col2', 'col3']
df_data = spark.read.format("com.crealytics.spark.excel") \
            .option("header", "true") \
            .option("dataAddress", f"'{sheet_name}'!A1") \
            .option("treatEmptyValuesAsNulls", "false") \
            .schema(schema) \
            .load(file_path)
df_data = df_data.select(desired_order)
df_data.show()

结果:

+----+----+----+
|col1|col2|col3|
+----+----+----+
|  12|  23|NULL|
|  34|  45|  56|
+----+----+----+

在上面的代码中,我读取了Excel文件,应用了指定的格式,并按照想要的顺序选择了列。

撰写回答