簡體   English   中英

使用python保存.xlsx文件時保持相同的文件格式

[英]keeping the same file format when saving .xlsx file using python

我正在一個項目中工作,我必須將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文件與輸入文件的格式不同(單元格寬度,粗體邊框)。 我該怎么做才能解決這個問題?

您無法保留格式,因為熊貓在導入時會丟棄所有這些信息。 您需要使用ExcelWriter對象在輸出中指定所需的格式設置選項。 如果使用選項engine='xlsxwriter' ,則可以在寫入最終文件之前使用所有xlsxwriter格式化選項。 您可以在XlsxWriter文檔中找到更多詳細信息

例:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM