有没有办法用Python向Excel表格添加新行?

0 投票
1 回答
2779 浏览
提问于 2025-04-18 17:41

我在网上查了很多资料,试过一些 win32comxlrd/xlwt/xlutils 的库,但我只能在现有的 Excel 行里插入数据。我想要的是能在 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

...接下来的部分是缩进的,因为它在一些循环里,不太会在 Stack Overflow 上格式化

        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'))

1 个回答

0

xlwt 是一个可以帮助你写入 Excel 文件的工具。

要在 Excel 中写入任何内容,你需要指定一个行和列的位置。就像这样:worksheet.write(x,y,x*y)。这个命令会在坐标为 x 和 y 的单元格中写入 x 乘以 y 的值。

所以,在你的情况下,如果想在新的一行写入内容,只需给出你想要的新行的行号,然后写入你想要的列数。很简单。

这不是一个需要你添加的列表。你可以直接跳到任何你想要的单元格进行写入。

这里有一个很有用的例子 - http://codingtutorials.co.uk/python-excel-xlrd-xlwt/

撰写回答