本文介绍了从 xls 文件中删除列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python,我需要能够对 excel 2007 的工作簿执行以下操作:

Using Python, I need to be able to do the following operations to a workbook for excel 2007:

1.删除列

我正在调查 xlrd;然而.

I am looking into xlrd; however.

谁能告诉我怎么做?

推荐答案

如果你在 Python 3.x 中工作,你会发现使用 xlrd/ 会遇到很多麻烦xlwt/xlutils 系列,因为它们是 Python 2 的模块.

If you're working in Python 3.x, you'll find a lot of trouble using the xlrd/xlwt/xlutils family, as they're modules for Python 2.

您可以考虑使用 openpyxl 来处理 Excel 2007 .Python 3 中的 xlsx 文件.

You might consider openpyxl for working with Excel 2007 .xlsx files in Python 3.

如果您只需要移动值(不考虑格式等),这是一种方法.您可以以此为基础:

If you just need to shift values over (disregarding formatting, etc) here's one way to do it. You can build on this:

from openpyxl import load_workbook
from openpyxl.cell import column_index_from_string as col_index
from openpyxl.cell import get_column_letter as col_letter

def del_col(s, col, cmax=None, rmax=None):
    col_num = col_index(col) - 1
    cols = s.columns
    if isinstance(cmax, str):
        cmax = col_index(cmax)
    cmax = cmax or s.get_highest_column()
    rmax = rmax or s.get_highest_row()
    for c in range(col_num, cmax + 1):
        # print("working on column %i" % c)
        for r in range(0, rmax):
            cols[c][r].value = cols[c+1][r].value
    for r in range(0, rmax):
        cols[c+1][r].value = ''

    return s

if __name__ == '__main__':
    wb = load_workbook('input_book.xlsx')
    ws = wb.active
    # or by name: ws = wb['SheetName']
    col = 'D'
    del_col(ws, col)
    wb.save('output_book.xlsx')

这篇关于从 xls 文件中删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 03:52