Hướng dẫn pandas text color excel - gấu trúc màu văn bản excel

The style.applymap is for showing output of dataframes in HTML, not updating excel sheets. You can change the code thus to update the font in excel. I am reading the excel input.xlsx, updating the contents using openpyxl and writing it to

import pandas as pd
import numpy as np
df = pd.read_excel('output.xlsx')
df.fillna('NA', inplace = True)

writer = pd.ExcelWriter('output1.xlsx')
df.to_excel(writer, sheet_name= 'sheet1', index=False)
worksheet = writer.sheets['sheet1']
workbook = writer.book
cell_format_red = workbook.add_format({'font_color': 'red'})
cell_format_green = workbook.add_format({'font_color': 'green'})

start_row = 1
start_col = 2
end_row = len(df)
end_col = start_col

worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '==', 'value': '"DATA"', 'format': cell_format_red})
worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '!=', 'value': '"DATA"', 'format': cell_format_green})

writer.save()
0. You can change other things like size, bold, fontname, etc. as well. Note: Color used is HEX color, but without the
import pandas as pd
import numpy as np
df = pd.read_excel('output.xlsx')
df.fillna('NA', inplace = True)

writer = pd.ExcelWriter('output1.xlsx')
df.to_excel(writer, sheet_name= 'sheet1', index=False)
worksheet = writer.sheets['sheet1']
workbook = writer.book
cell_format_red = workbook.add_format({'font_color': 'red'})
cell_format_green = workbook.add_format({'font_color': 'green'})

start_row = 1
start_col = 2
end_row = len(df)
end_col = start_col

worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '==', 'value': '"DATA"', 'format': cell_format_red})
worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '!=', 'value': '"DATA"', 'format': cell_format_green})

writer.save()
1 symbol in front

import openpyxl

wb = openpyxl.load_workbook(filename="input.xlsx")
ws = wb.active

for row in range(2,ws.max_row+1): #Skipping first row as I assume it is header
    if ws.cell(row=row, column=3).value == 'DATA':
        ws.cell(row=row, column=3).font = openpyxl.styles.Font(color='FF0000') #, size=16, bold=True, name='Calibri')
    else:
        ws.cell(row=row, column=3).font = openpyxl.styles.Font(color='C6E2E9')
wb.save("output.xlsx")

USING pandas.ExcelWriter instead of openpyxl You can use the below code pandas.ExcelWriter to change the font to RED for DATA and GREEN for others. Note: you can edit the colors to anything you want using # followed by the 6 char hexcode in case you want to change the font color You can use the below code pandas.ExcelWriter to change the font to RED for DATA and GREEN for others. Note: you can edit the colors to anything you want using # followed by the 6 char hexcode in case you want to change the font color

import pandas as pd
import numpy as np
df = pd.read_excel('output.xlsx')
df.fillna('NA', inplace = True)

writer = pd.ExcelWriter('output1.xlsx')
df.to_excel(writer, sheet_name= 'sheet1', index=False)
worksheet = writer.sheets['sheet1']
workbook = writer.book
cell_format_red = workbook.add_format({'font_color': 'red'})
cell_format_green = workbook.add_format({'font_color': 'green'})

start_row = 1
start_col = 2
end_row = len(df)
end_col = start_col

worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '==', 'value': '"DATA"', 'format': cell_format_red})
worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '!=', 'value': '"DATA"', 'format': cell_format_green})

writer.save()

Nội dung chính ShowShow

  • Không tùy chỉnh
  • Ít tùy chỉnh
  • Tùy chỉnh đầy đủ
  • bài chuyển hướng
  • Tôi có thể sử dụng openpyxl và gấu trúc với nhau không?
  • Làm cách nào để thay đổi định dạng ô trong openpyxl?
  • Cái gấu trúc nào tốt hơn hoặc openpyxl?
  • OpenPyxl có thể viết các tệp XLS không?

OpenPyXL là thư viện Python để đọc và ghi các tệp XLSX/XLSM/XLSM/XLTX/XLTM Excel 2010..

Nội dung chính Show

import pandas as pd
from io import StringIO

df = pd.read_csv(StringIO("""\
               alpha      beta     gamma
2000-01-01 -0.173215  0.119209 -1.044236
2000-01-02 -0.861849 -2.104569 -0.494929
2000-01-03  1.071804  0.721555 -0.706771
2000-01-04 -1.039575  0.271860 -0.424972
2000-01-05  0.567020  0.276232 -1.087401
2000-01-06 -0.673690  0.113648 -1.478427
2000-01-07  0.524988  0.404705  0.577046
2000-01-08 -1.715002 -1.039268 -0.370647
"""), sep="\s+", parse_dates=True)

output_filename = 'pandas-to-excel.xlsx'

Không tùy chỉnh

Ít tùy chỉnh

sheet_name = 'No customization'
df.to_excel(output_filename, sheet_name)

Ít tùy chỉnh

Tùy chỉnh đầy đủ

with pd.ExcelWriter(
        output_filename,
        mode='a',  # append; default='w' (overwrite)
        engine='openpyxl') as xlsx:
    sheet_name = 'Little customization'
    df.to_excel(xlsx, sheet_name)
    
    # set index column width
    ws = xlsx.sheets[sheet_name]
    ws.column_dimensions['A'].width = 21

Tùy chỉnh đầy đủ

Khi tôi muốn lưu trạng thái hiện tại của GANDAS DATAFRAME cho tiêu thụ thủ công trên mạng, tôi thường viết

import pandas as pd
import numpy as np
df = pd.read_excel('output.xlsx')
df.fillna('NA', inplace = True)

writer = pd.ExcelWriter('output1.xlsx')
df.to_excel(writer, sheet_name= 'sheet1', index=False)
worksheet = writer.sheets['sheet1']
workbook = writer.book
cell_format_red = workbook.add_format({'font_color': 'red'})
cell_format_green = workbook.add_format({'font_color': 'green'})

start_row = 1
start_col = 2
end_row = len(df)
end_col = start_col

worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '==', 'value': '"DATA"', 'format': cell_format_red})
worksheet.conditional_format(start_row, start_col, end_row, end_col, {'type': 'cell', 'criteria': '!=', 'value': '"DATA"', 'format': cell_format_green})

writer.save()
2 trong phiên ipython hoặc sổ ghi chép Jupyter của mình. Tuy nhiên, kiểu mặc định trông không đẹp và thường cần điều chỉnh thủ công (ví dụ: chiều rộng cột) để có thể sử dụng được.

  • Nếu bạn muốn tạo các báo cáo tùy chỉnh từ gấu trúc, do đó bạn có thể muốn theo chương trình kiểu này. Gói openpyxl thực hiện công việc này độc đáo. Dưới đây là một ví dụ động lực cho bạn thấy những cách cơ bản của API. Đầu tiên, có một số dữ liệu ngẫu nhiên:
  • Chỉ để so sánh, xuất bản đơn giản của DataFrame sang bảng tính đầu tiên:
  • Áp dụng một kiểu được xây dựng được đặt tên theo tên (tiêu đề 2) cho hàng tiêu đề.
  • Tạo và áp dụng một kiểu tùy chỉnh được đặt tên (kiểu chỉ mục) bao gồm định dạng số, phông chữ và căn chỉnh.

Đầu tiên, các định nghĩa nhập khẩu và quy tắc/kiểu:

from openpyxl.formatting.rule import ColorScaleRule
from openpyxl.styles import Alignment, Font, NamedStyle
from openpyxl.utils import get_column_letter

percentile_rule = ColorScaleRule(
    start_type='percentile',
    start_value=10,
    start_color='ffaaaa',  # red-ish
    mid_type='num',
    mid_value=0,
    mid_color='ffffff',  # white
    end_type='percentile',
    end_value=90,
    end_color='aaffaa')  # green-ish
    
# custom named style for the index
index_style = NamedStyle(
    name="Index Style",
    number_format='YYYY-MM-DD, DDD',
    font=Font(color='999999', italic=True),
    alignment=Alignment(horizontal='left'))

# pass keyword args as dictionary
writer_args = {
    'path': output_filename,
    'mode': 'a',
    'engine': 'openpyxl'}

Cùng với đó, văn bản thực tế trông như thế này:

with pd.ExcelWriter(**writer_args) as xlsx:
    sheet_name = 'Full customization'
    df.to_excel(xlsx, sheet_name)
    ws = xlsx.sheets[sheet_name]
    
    # cell ranges
    index_column = 'A'
    value_cells = 'B2:{col}{row}'.format(
        col=get_column_letter(ws.max_column),
        row=ws.max_row)
    title_row = '1'

    # index column width
    ws.column_dimensions[index_column].width = 21

    # color all value cells
    ws.conditional_formatting.add(value_cells, 
                                  percentile_rule)
    
    # for general styling, one has to iterate over
    # all cells individually
    for row in ws[value_cells]:
        for cell in row:
            cell.number_format = '0.00'
    
    # builtin or named styles can be applied by using
    # the style object or their name (shown below)
    for cell in ws[index_column]:
        cell.style = index_style
    
    # style title row last, so that headline style
    # wins over index style in top-left cell A1
    for cell in ws[title_row]:
        cell.style = 'Headline 2'

Nếu bạn muốn ở trên trong một tập lệnh, hãy thử gist pandas-to-excel.py của tôi. Nó tạo ra một tệp excel duy nhất với ba bảng tính được đặt tên phù hợp.

bài chuyển hướng

Tôi có thể sử dụng openpyxl và gấu trúc với nhau không?

Tải dữ liệu Excel với OpenPyXL và chuyển đổi thành DataFrame. DataFrame được sử dụng để biểu diễn dữ liệu 2D trên gấu trúc. Vì dữ liệu Excel cũng là dữ liệu 2D được biểu thị bằng các hàng và cột, đối tượng bảng tính trong [openpyxl] (https://openpyxl.readthedocs.io/en/stable/index.html) có thể được chuyển đổi thành đối tượng DataFrame Pandas.Worksheet object in [openpyxl] (https://openpyxl.readthedocs.io/en/stable/index.html) can be converted to Pandas DataFrame object.Worksheet object in [openpyxl] (https://openpyxl.readthedocs.io/en/stable/index.html) can be converted to Pandas DataFrame object.

Làm cách nào để thay đổi định dạng ô trong openpyxl?

Chúng ta hãy xem chương trình sau:...

nhập openpyxl ..

WB = OpenPyxl.load_workbook ('Marks. xlsx').

Tờ = WB.tích cực..

Tế bào = tấm ['A1', 'B7'].

# Các tế bào hoạt động như toán tử phạm vi ..

Đối với I1, I2 trong các tế bào:.

print ("{0: 8} {1: 8}". định dạng (i1. value, i2. value)).

Cái gấu trúc nào tốt hơn hoặc openpyxl?

Theo cộng đồng Stackshare, Pandas có sự chấp thuận rộng hơn, được đề cập trong 41 Stacks & 83 nhà phát triển của công ty;So với OpenPyXL, được liệt kê trong 7 ngăn xếp công ty và 7 ngăn xếp nhà phát triển.pandas has a broader approval, being mentioned in 41 company stacks & 83 developers stacks; compared to openpyxl, which is listed in 7 company stacks and 7 developer stacks.pandas has a broader approval, being mentioned in 41 company stacks & 83 developers stacks; compared to openpyxl, which is listed in 7 company stacks and 7 developer stacks.

OpenPyxl có thể viết các tệp XLS không?

OpenPyXL là thư viện Python để đọc và ghi các tệp XLSX/XLSM/XLSM/XLTX/XLTM Excel 2010...