【问题标题】:keeping the same file format when saving .xlsx file using python使用python保存.xlsx文件时保持相同的文件格式
【发布时间】:2018-07-18 22:23:57
【问题描述】:

我正在做一个项目,我必须将 excel 文件更改为数据并保存

from pandas import ExcelWriter
import pandas as pd

dfs = pd.read_excel("infile.xlsx")

#manuplate data 

writer = ExcelWriter('outfile.xlsx')
dfs.to_excel(writer,'Sheet5')
writer.save()

我遇到的问题是新保存的 excel 文件与输入文件的格式(单元格宽度、粗边框)不同。我该怎么做才能解决这个问题?

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    您无法保留格式,因为 pandas 在导入时会丢弃所有这些信息。您需要使用 ExcelWriter 对象在输出中指定所需的格式选项。如果您使用选项engine='xlsxwriter',则可以在写入最终文件之前使用所有 xlsxwriter 格式化选项。您可以在XlsxWriter documentation.中找到更多详细信息

    例子:

    import pandas as pd
    
    # This removes the default header style so we can override it later
    import pandas.io.formats.excel
    pandas.io.formats.excel.header_style = None
    
    
    # Create a Pandas dataframe from some data.
    df = pd.DataFrame({'Data1': [10, 20, 30, 20, 15, 30, 45],
                       'Data2': [90, 80, 30, 15, 88, 34, 41]})
    
    
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1')
    
    # Get the xlsxwriter workbook and worksheet objects.
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']
    
    # Create Format objects to apply to sheet
    # https://xlsxwriter.readthedocs.io/format.html#format-methods-and-format-properties
    red_bold = workbook.add_format({'bold': True, 'font_color': 'red'})
    border = workbook.add_format({'border':5, 'border_color':'blue'})
    
    #Apply formatting to sheet
    worksheet.set_column('C:C', None, red_bold)
    worksheet.set_column('A1:A8', None, border)
    
    # Apply a conditional format to a cell range.
    worksheet.conditional_format('B2:B8', {'type': '3_color_scale'})
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    

    【讨论】:

    • 听起来解决方案的正确方向。有机会,您能否在答案中提供代码示例?
    • 为您更新了一个示例。
    • 是的,您可以为您在 python 代码上创建的数据设置格式。但是,我遇到的问题是从 .xlsx 文件中提取格式并将相同的格式应用于新创建的 .xlsx
    • 你知道怎么做吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2011-10-24
    • 2013-08-10
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多