如何从数组中写入 excel 中的整行 - xlwt
How to write a entire row in excel from an array - xlwt
我想改进我的代码,替换为:
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']
column =0
for h in header:
sheet.write(0, column, h)
column += 1
有些代码直接用数组头来写一整行。有什么想法吗?
您不太可能通过将数据写入行单元来获得任何实际改进,因为 Excel 以任何一种方式单独存储单元格。这可能就是为什么 xlwt
.
没有记录这样的方法的原因
您可以使用枚举将代码减少几行:
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']
for column, heading in enumerate(header):
sheet.write(0, column, heading)
如果您发现自己经常做这种事情,请编写一个实用的小方法:
def write_header(header, row=0, start_col=0):
for column, heading in enumerate(header, start_col):
sheet.write(row, column, heading)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
write_header([u'Nome da estação',u'Altitude',u'Latitude',u'Longitude'])
附加参数将允许您在需要时设置电子表格中 header 的 upper-left 角。默认值应涵盖 99% 的用例。
只有sheet.write()
,写给row_index, column_index
。
如果您担心速度或优化,只需专注于优化 for
循环,就像您对任何其他编程流程所做的那样。
workbook.save()
最后只需要一次 - 所以文件 I/O 仍然只发生一次。
我想改进我的代码,替换为:
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']
column =0
for h in header:
sheet.write(0, column, h)
column += 1
有些代码直接用数组头来写一整行。有什么想法吗?
您不太可能通过将数据写入行单元来获得任何实际改进,因为 Excel 以任何一种方式单独存储单元格。这可能就是为什么 xlwt
.
您可以使用枚举将代码减少几行:
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']
for column, heading in enumerate(header):
sheet.write(0, column, heading)
如果您发现自己经常做这种事情,请编写一个实用的小方法:
def write_header(header, row=0, start_col=0):
for column, heading in enumerate(header, start_col):
sheet.write(row, column, heading)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS")
write_header([u'Nome da estação',u'Altitude',u'Latitude',u'Longitude'])
附加参数将允许您在需要时设置电子表格中 header 的 upper-left 角。默认值应涵盖 99% 的用例。
只有sheet.write()
,写给row_index, column_index
。
如果您担心速度或优化,只需专注于优化 for
循环,就像您对任何其他编程流程所做的那样。
workbook.save()
最后只需要一次 - 所以文件 I/O 仍然只发生一次。