Python xlwings 操作Excel

Python xlwings 操作Excel

  • 导入 xlwings
  • Excel 操作

导入 xlwings

官方文档 https://docs.xlwings.org/en/stable/vba.html
按照图示,安装 xlwings
Python xlwings 操作Excel_第1张图片

Excel 操作

import xlwings as xw


def Operation_Excel(path):
    app = xw.App(visible=False, add_book=False)
    app.display_alerts = False
    app.screen_updating = False
    wb = app.books.open(path)
    try:
        sht = wb.sheets[0]
        rng = sht['A1:D2']  # 取出 A1:D2 单元格内的数据
        print(rng.value)
        s = ''
        for i in range(0, len(rng.value)):  # 循环行
            s += ','.join(
                filter(lambda x: x != 'None', map(str, rng.value[i]))) + ' '  # 把行数据先转str,然后去除为None的单元格,剩余的用逗号拼接
        # list(map(lambda x: print_str(x), rng))

        sht.range('E1:H2').clear()  # 清空 E1:H2
        sht.range('E1:H2').merge()  # 合并 E1:H2
        sht.range('E1').value = s  # 把合并的内容 填写在合并后的单元格内
        wb.save()
        print(s)
        wb.close()
        app.quit()
    except Exception as e:
        print(e.args)
        wb.close()
        app.quit()


file_path = r"..\files\demo.xlsx"  # 文件相对路径

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    Operation_Excel(file_path)

你可能感兴趣的:(Excel,#,Python,笔记,Python,python,开发语言)