0

我四处搜索,尝试了win32com一些xlrd// xlwtxlutils但我所能做的就是将数据插入现有的 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'))
4

1 回答 1

0

xlwt 帮助你写出 excel。

要写任何东西到excel,你必须指定一行和一列所以就像worksheet.write(x,y,x*y) 这个命令用x写入一个单元格,y坐标x * y的值。

因此,在您的情况下,要写入新行,只需在您想要新行的位置给出行号,然后写入尽可能多的列。简单的。

它不是您需要附加到的列表。你可以跳到任何你想写的单元格。

在这里查看一个有用的示例 - http://codingtutorials.co.uk/python-excel-xlrd-xlwt/

于 2014-08-18T18:12:05.450 回答