Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Enhance your career with this limited time 50% discount on Fabric and Power BI exams. Ends August 31st. Request your voucher.

Reply
Jeanxyz
Impactful Individual
Impactful Individual

how to write a spark dataframe into csv file without losing column headers

I have created a notebook and a spark data frame, when I write the data frame into a csv file, the column header is not written into csv. Is that normal?

***

yearlySales = df.select(year(col("OrderDate")).alias("Year")).groupBy("Year").count().orderBy("Year")

yearlySales.write.mode("overwrite").format("csv").save("Files/yearlySales.csv")

***

 

1 ACCEPTED SOLUTION
nilendraFabric
Super User
Super User

Hi @Jeanxyz 

 

yearlySales.write.mode("overwrite").option("header", True).format("csv").save("Files/yearlySales.csv")

 

option(“header”, True): Ensures that the column headers are written as the first row in the CSV output.

 

View solution in original post

3 REPLIES 3
v-saisrao-msft
Community Support
Community Support

Hi @Jeanxyz,

Thank you for reaching out to the Microsoft Fabric Forum Community. 

Check the solution provided by @nilendraFabric, adding.option("header", True) to your .write() operation will ensure the column headers are written as the first row in your CSV file. 

You can also refer to the official Apache Spark documentation for more context on the header option: 

vsaisraomsft_0-1748248760154.png

 

CSV Files - Spark 3.3.2 Documentation 

 

If this post helps, then please give us ‘Kudos’ and consider Accept it as a solution to help the other members find it more quickly.

 

Thank you. 

Jeanxyz
Impactful Individual
Impactful Individual

Thanks a lot, @nilendraFabric . This works. I have yet another question. What's the best Spark tutorial online? I searched on https://spark.apache.org/, but the documentation about dataframe write method seems quite limited.

Screenshot 2025-05-26 100239.png

 

nilendraFabric
Super User
Super User

Hi @Jeanxyz 

 

yearlySales.write.mode("overwrite").option("header", True).format("csv").save("Files/yearlySales.csv")

 

option(“header”, True): Ensures that the column headers are written as the first row in the CSV output.

 

Helpful resources

Announcements
Join our Fabric User Panel

Join our Fabric User Panel

This is your chance to engage directly with the engineering team behind Fabric and Power BI. Share your experiences and shape the future.

June FBC25 Carousel

Fabric Monthly Update - June 2025

Check out the June 2025 Fabric update to learn about new features.

June 2025 community update carousel

Fabric Community Update - June 2025

Find out what's new and trending in the Fabric community.

Top Solution Authors