使用 xlsxwriter 合并每隔一个单元格
Posted
技术标签:
【中文标题】使用 xlsxwriter 合并每隔一个单元格【英文标题】:Merge every second cell with xlsxwriter 【发布时间】:2019-12-01 02:53:06 【问题描述】:我希望每隔一个单元格与 xlsxwriter 合并,如下所示。
我试过了
import xlsxwriter, os, datetime as dt
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('AARs.xlsx')
worksheet = workbook.add_worksheet()
# Create a format to use in the merged range.
merge_format = workbook.add_format(
'align': 'center',
'valign': 'vcenter')
# Start and end dates of the trial to go into the spreadsheet.
start_date = dt.datetime(2019, 8, 6)
end_date = dt.datetime(2019, 12, 13)
trial_length = end_date -start_date
# Merge cells.
for days in range(trial_length.days):
worksheet.merge_range(1, 1+days, 1, 2+days, 'Merged Range', merge_format)
workbook.close()
我已经明确写出了下面的for循环
worksheet.merge_range(1, 1, 1, 2, 'Merge Range', merge_format)
worksheet.merge_range(1, 3, 1, 4, 'Merge Range', merge_format)
worksheet.merge_range(1, 5, 1, 6, 'Merge Range', merge_format)
worksheet.merge_range(1, 7, 1, 8, 'Merge Range', merge_format)
worksheet.merge_range(1, 9, 1, 10, 'Merge Range', merge_format)
worksheet.merge_range(1, 11, 1, 12, 'Merge Range', merge_format)
worksheet.merge_range(1, 13, 1, 14, 'Merge Range', merge_format)
worksheet.merge_range(1, 15, 1, 16, 'Merge Range', merge_format)
worksheet.merge_range(1, 17, 1, 18, 'Merge Range', merge_format)
worksheet.merge_range(1, 19, 1, 20, 'Merge Range', merge_format)
我现在只是无法编写正确的循环。我尝试过类似的方法:
count_odd = 0
count_even = 0
for days in range(trial_length.days):
if not days % 2:
worksheet.merge_range(1, 1, 1, 2 + count_even, 'Merge Range', merge_format)
count_even += 1
else:
worksheet.merge_range(1, 1 + count_odd, 1, 2 + count_even, 'Merge Range', merge_format)
count_odd += 1
但这似乎也不起作用。 我正在尝试合并每隔一个单元格。
【问题讨论】:
看起来不错和看起来不对是什么意思? @AlexanderCécile 我添加了它在 Linux 中的显示方式 如果我理解正确的话,days + 1
和之前迭代的days + 2
不一样吗?
忘了说变量和函数名一般应该遵循lower_case_with_underscores
风格。
【参考方案1】:
想通了。
odd = 1
even = 2
for day in range(trial_length.days):
worksheet.merge_range(1, odd, 1, even, 'Merge Range', merge_format)
odd += 2
even += 2
答案几乎太明显了。
【讨论】:
以上是关于使用 xlsxwriter 合并每隔一个单元格的主要内容,如果未能解决你的问题,请参考以下文章
根据值合并行(熊猫到 excel - xlsxwriter)
如何强制Python XlsxWriter以自定义格式写入单元格