Код ниже работает нормально:
import re
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True, 'color': 'red'})
# Some sample test data.
string = 'A best is the best'
command = 'best'
regex = r'(' + command + ')'
segments = re.split(regex, string)
if len(segments) == 1:
# String doesn't have a match, write as a normal string.
worksheet.write(0, 0, string)
else:
# Iternate through the segments and add a format before the matches.
tmp_array = []
for segment in segments:
if segment == command:
# Add a bold format before the matched word.
tmp_array.append(bold)
tmp_array.append(segment)
elif not segment:
# Ignore blank segments.
pass
else:
tmp_array.append(segment)
worksheet.write_rich_string(0, 0, *tmp_array)
workbook.close()
Теперь я хочу прочитать данные из test.xlsx
с помощью pandas и применить форматирование к этим данным с помощью xlsxwriter, а затем сохранить данные в новом Excel testNew.xlsx
. Я следовал за этой статьей . Вот мой код, который работает не так, как ожидалось:
import xlsxwriter
import pandas as pd
import re
df = pd.read_excel(r'C:\Users\test.xlsx')
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('testNew.xlsx', engine ='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Set up some formats to use.
blue = workbook.add_format({'color': 'blue'})
command = 'best'
string = df.iat[0,0] #########THROWS ERROR################
regex = r'(' + command + ')'
segments = re.split(regex, string)
if len(segments) == 1:
# String doesn't have a match, write as a normal string.
worksheet.write(0, 0, string)
else:
# Iternate through the segments and add a format before the matches.
tmp_array = []
for segment in segments:
if segment == command:
tmp_array.append(blue)
tmp_array.append(segment)
elif not segment:
# Ignore blank segments.
pass
else:
tmp_array.append(segment)
worksheet.write_rich_string(0, 0, *tmp_array)
writer.save()
Он выдает ошибку ниже:
Exception has occurred: IndexError
index 1 is out of bounds for axis 0 with size
Что я здесь не так делаю?