Python Excel批处理

保存下面的代码为excelbatch.py:

from sys import argv
from openpyxl import load_workbook
from openpyxl.utils import column_index_from_string as str_to_int
from math import *

NO_ENOUGH_ARGS_ERROR = 1
MODE_ERROR = 2
NO_SUCH_FILE_ERROR = 3
NO_SUCH_SHEET_ERROR = 4
BATCH_CODE_RUN_ERROR = 5
BAD_CELL_NAME_ERROR = 6

if len(argv) < 6:
    print('Usage: %s [excel-filename] [sheet-name] [mode(range/single)] [batch-code] [*cells(single)]/<[start-cell] [end-cell](range)>' % argv[0])
    exit(NO_ENOUGH_ARGS_ERROR)

fp = argv[1]
sname = argv[2]
mode = argv[3]
if mode not in ['range', 'single']:
    print('Error: mode must be range/single')
    exit(MODE_ERROR)
batchcode = argv[4]
if mode == 'range':
    start, end = argv[5:]

try:
    wb = load_workbook(fp)
except:
    print('Error: No such excel file')
    exit(NO_SUCH_FILE_ERROR)

try:
    sheet = wb.get_sheet_by_name(sname)
except:
    print('Error: No such sheet')
    exit(NO_SUCH_SHEET_ERROR)

if mode == 'range':
    try:
        for row in sheet[start:end]:
            for col in row:
                try:
                    col.value = eval(batchcode.replace('cell', str(col.value)))
                except:
                    print('Error: Batch code run error')
                    exit(BATCH_CODE_RUN_ERROR)
    except:
        print('Error: Bad cell name')
        exit(BAD_CELL_NAME_ERROR)
else:
    try:
        for cell in argv[5:]:
            try:
                sheet[cell].value = eval(batchcode.replace('cell', str(sheet[cell].value)))
            except:
                print('Error: Batch code run error')
                exit(BATCH_CODE_RUN_ERROR)
    except:
        print('Error: Bad cell name')
        exit(BAD_CELL_NAME_ERROR)

wb.save(fp)

按照代码里的提示运行就好啦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值