我想使用 pandas 将 2 个字符串写入 xlsx 文件中的一列
超链接的部分是可点击的。 “- 发行说明选项卡”不应成为超链接的一部分。就像屏幕截图中的那样。
我正在尝试这样的事情。我想写的专栏称为“已知问题”。请参阅
if 'Known Issues' in df:
线。
def create_excel_with_format(headers,values,full_file_name_with_path):
#Write to CSV in xlsx format with indentation.
df = pd.DataFrame(data=values,columns=headers)
#df = df.set_axis(df.index*2 + 1).reindex(range(len(df)*2)) #Create a blank row after every row.
with pd.ExcelWriter(full_file_name_with_path) as writer:
#For any list items inside of the excel file we remove the square brackets[]
for index,row in df.iterrows():
for col in list(df.columns):
if isinstance(row[col], list):
row[col] = ", ".join(row[col])
df.to_excel(writer, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
#Write the location each comma separated in new line if exists (For Nuget exists and thirdparty no).
if 'Location' in df:
df["Location"] = df["Location"].str.join("\n")
twrap = workbook.add_format({"text_wrap": True})
idx_location = df.columns.get_loc("Location")
worksheet.set_column(idx_location, idx_location, 60, twrap)
if 'Known Issues' in df:
df["Known Issues"]=df["Known Issues"].str.join(" - release notes tab") #DOES NOT WORK
header_format = workbook.add_format({
'bold': True,
'border': False,
'text_wrap': False,
'font_size':13})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
我重写了你的函数(但我没有测试代码,就像你没有提供示例一样)。
我认为问题在于你的第一个
for
循环的位置,因为在应用 join
函数之前,你可以通过将所有列表项转换为字符串来删除它们......这需要提供一个列表。
您的方法应该是进行所有您需要的
join
治疗,然后再删除剩余的列表。
def create_excel_with_format(headers,values,full_file_name_with_path):
df = pd.DataFrame(data=values,columns=headers)
with pd.ExcelWriter(full_file_name_with_path) as writer:
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# df treatments first
if 'Location' in df:
df['Location'] = df['Location'].apply(lambda x: "\n".join(x) if isinstance(x, list) else x)
if 'Known Issues' in df:
df['Known Issues'] = df['Known Issues'].apply(lambda x: x + " - release notes tab" if pd.notnull(x) else x)
# For any list items inside of the excel file we remove the square brackets[]
df = df.applymap(lambda x: ", ".join(x) if isinstance(x, list) else x)
# ...
if 'Location' in df:
twrap = workbook.add_format({"text_wrap": True})
idx_location = df.columns.get_loc("Location")
worksheet.set_column(idx_location, idx_location, 60, twrap)
df.to_excel(writer, index=False)
header_format = workbook.add_format({
'bold': True,
'border': False,
'text_wrap': False,
'font_size':13})