我四处搜索,尝试了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'))