Python操作Excel

本代码的是从sheet2中把一个table类型的数据嵌入到sheet1中的模版中。这里table的内容从abap中迭代插入的,但是由于Excel中不能做table类型的cell合并,所以只能插入其他的地方做cell合并
1.创建VBA宏

Sub helloworld()
    RunPython "import hello; hello.world()"
End Sub

2.同时在VBA中插入xlwings的引用
3.hello文件的内容

import xlwings as xw
from xlwings.constants import InsertShiftDirection
def world():
    wb = xw.Book.caller()
    sht1 = wb.sheets[0]
    sht2 = wb.sheets[1]
    table_content = sht2.tables[0].range.rows.rng.value
    table_content.reverse()
    index = 11
    for i in table_content:
        #sht1.range('11:11').insert()
        sht1.range('11:11').api.Insert(InsertShiftDirection.xlShiftDown)
        sht1.range('A11').value = i[0]
        sht1.range('B11').value = i[1]
        sht1.range('C11').value = i[2]
        sht1.range('C11:G11').merge()
        sht1.range('H11').value = i[3]
        sht1.range('I11').value = i[4]
        sht1.range('J11').value = i[5]
        sht1.range('J11:K11').merge()
        sht1.range('L11').value = i[6]
        sht1.range('L11:M11').merge()
        sht1.range('N11').value = i[7]
        sht1.range('N11:P11').merge()
        index += 1
    sht1.range(str(index) + ':' + str(index)).delete()

你可能感兴趣的:(Python操作Excel)