从现有工作簿中删除行和列 sheet

Delete rows and cols from exist workbook sheet

我正在尝试从 sheet 中删除除前三行和所有从坐标 (U - AA) 开始的列之外的所有填充行。我必须删除所有填写的信息,除了最后的headers。如何删除我不明白的列,但是当我 运行 删除行的脚本时,信息被保留,只有样式被删除。如何正确执行这样的操作?

class DownloadRfiExcelFile(APIView):
    """
    Download rfi excel file to user
    """
    def get(self, request, format=None, **kwargs):
        file = default_storage.url('test.xlsx')
        wb = load_workbook(filename=file)

        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename="test.xlsx"'
        sheet = wb["RT"]
        for rowNum in range(3, 1114):
                sheet.delete_rows(rowNum)
        for col in sheet.iter_cols():
            for cell in col:
                # delete from U to AA row
        wb.save(response)
        return response

要删除 rowscolumns 只需使用:

  • sheet.delete_rows({first_row}, {amount})
  • sheet.delete_cols({first_col}, {amount})

因此,请阅读 openpyxl documentation 中的更多信息。请注意,列表示为整数,因此 A == 1, B ==2 依此类推。

import string

def col2num(col):
    # Utility function to convert column letters to numbers

    num = 0
    for c in col:
        if c in string.ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

# Setting initial values for deletion
starting_row = 4
starting_col = col2num('U')
last_col = col2num('AA')

# Deleting rows and columns
sheet.delete_rows(starting_row, sheet.max_row-starting_row)
sheet.delete_cols(starting_col, last_col-starting_col)

openpyxl.utils有一个将列字符串转换为整数的函数:column_index_from_string

所以使用可以只导入它而不是编写自己的函数:

from openpyxl.utils import column_index_from_string as col2num

# Setting initial values for deletion
...

column_index_from_string 使用 openpyxls 内部 _COL_STRING_CACHE 查找列字符串。我不知道它是否更快,但我想在大多数情况下,内置的会很好。