我搜索了一下,尝试了一些win32com
和一些xlrd
/ xlwt
/ xlutils
但我所能做的就是将数据插入现有的Excel行 - 我想要能够插入一个新行(特别是第一个,在我的情况下)。有谁知道如何使用Python做到这一点?
根据建议,我将包括我在excel文件中添加行的内容
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
import xlwt
...下一部分是缩进的,因为它在某些for循环中,不擅长堆栈溢出格式化
rb = open_workbook( os.path.join(cohort_path, f),on_demand=True,encoding_override="cp1252",formatting_info=True)
#The following is because Messed up file has a missing row
if f=='MessedUp.xls':
r_sheet = rb.sheet_by_name('SHEET NAME') # read only copy to introspect the file
wb = copy(rb)
w_sheet = wb.get_sheet(rb.sheet_names().index('SHEET NAME')) #Workaround
#fix first rows
for col_index in range(0, r_sheet.ncols):
for row_index in range(2, r_sheet.nrows):
xfx = r_sheet.cell_xf_index(row_index-1, col_index)
xf = rb.xf_list[xfx]
bgx = xf.background.pattern_colour_index
xlwt.add_palette_colour("custom_colour", 0x17)
#rb.set_colour_RGB(0x21, 251, 228, 228) #or wb??
style_string = 'pattern: pattern solid, fore_colour custom_colour' if bgx in (55,23) else None
style = xlwt.easyxf(style_string)
w_sheet.write(row_index, col_index, r_sheet.cell(row_index-1,col_index).value,style=style)
wb.save(os.path.join(cohort_path, 'fixed_copy.xls'))
答案 0 :(得分:0)
xlwt帮助您写入excel。
要向Excel写入任何内容,您必须指定行和列
就像worksheet.write(x,y,x*y)
一样
此命令写入带有x,y的单元格,用于协调x * y的值。
因此,在您的情况下,要写入新行,只需将行号放在您想要新行的位置, 并写出你想要的列。简单。
它不是您需要追加的列表。您可以跳转到任何想要的单元格并写入。
在此处查看一个有用的示例 - http://codingtutorials.co.uk/python-excel-xlrd-xlwt/