简体   繁体   English

无法使用熊猫和xlsxwriter将格式添加到Excel工作表

[英]unable to add formatting to excel sheet using pandas and xlsxwriter

I'm able to transfer data from datafile.xlsx to test.xlsx, but I don't know how to add the color red to specific cells in test.xlsx 我可以将数据从datafile.xlsx传输到test.xlsx,但是我不知道如何将红色添加到test.xlsx中的特定单元格

#The major components of the code are shown below #代码的主要组成部分如下所示

import pandas as pd 
import xlsxwriter

file = "datafile.xlsx"
xlsx = pd.ExcelFile(file)
sheet1 = xlsx.parse(0)
writer = pd.ExcelWriter("test.xlsx")
columns=["FirstName", "MiddleName", "LastName", ......]

#--My code doesn't work when a sheet_name is added in the to_excel piece--

dfc = pd.DataFrame([columns])
dfc.to_excel(writer,sheet_name=sheet1, startrow=0, startcol=0, 
index=False, header=None) 

#The body of the code retrieves data from datafile.xlsx
#example--> row = sheet1.iloc[i].real

#---This section has my new code for adding cell color-----
#---cell color code(I define a workbook and worksheet)
workbook  = writer.book
worksheet = writer.sheets['sheet1']
cell_format = workbook.add_format()  
cell_format.set_font_color('red')
worksheet.write(0, 0, 'Foo', cell_format)
#----cell color code

dt = [row[0], row[1], row[2], .....]
df1 = pd.DataFrame([dt])
df1.to_excel(writer, startrow=rownum, startcol=0, index=False, header=None)  
writer.save()

If what you want is to change the color of the cell and not the color of the font then change 如果您要更改的是单元格的颜色而不是字体的颜色,请更改

cell_format.set_font_color('red')

for 对于

cell_format.set_bg_color('red')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM