0 values disappear for st.download_button

Dataframe have SKU column and it is str data type as well.
Dataframe have no problem to show SKU proper. For example, SKU 00729.
However, when I downloaded it the SKU become 729. 0 values disappear.
Any advice to fix it?
Here is some of my code.

st.markdown(β€˜# CES Price (View All)’)
# Execute the stored procedure
cursor.execute(β€œ{CALL usp_ces_price_all}”)

            # Fetch the results
            result_set = cursor.fetchall()
            columns = [column[0] for column in cursor.description]
            data = [dict(zip(columns, row)) for row in result_set]
            Ces_all_prices = pd.DataFrame(data)
            # Converting Dataframe to CSV file
            def convert_df(df):
                return df.to_csv(index=False).encode('utf-8')

            Ces_all_prices = convert_df(Ces_all_prices)
               "Export CES Price",
               Ces_all_prices ,
               mime='text/csv', type = 'primary')


You can modify your convert_df function to specify the data type for the SKU column

def convert_df(df):
    # Specify the dtype for the SKU column
    df['SKU'] = df['SKU'].astype(str)
    # Convert DataFrame to CSV file
    csv_data = df.to_csv(index=False, encoding='utf-8')
    return csv_data

Try to open the downloaded csv with notepad or notepad++ and see the sku number.

Hello @dom0574,

You can modify your convert_df function to ensure that leading zeros in the SKU column are preserved when the CSV is opened in Excel

import pandas as pd
import csv

def convert_df(df):
    # Use StringIO to avoid writing to disk
    from io import StringIO
    output = StringIO()
    # Ensure all fields are quoted so Excel treats them as strings
    df.to_csv(output, index=False, encoding='utf-8', quoting=csv.QUOTE_NONNUMERIC, quotechar='"')
    return output.getvalue().encode('utf-8')

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➀ Want me to build your solution? Lets chat about how I can assist!
➀ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➀ Website: https://sahirmaharaj.com
➀ Email: sahir@sahirmaharaj.com
➀ 100+ FREE Power BI Themes: Download Now