不改变原excel格式添加新数据

  • 背景介绍

    在实际工作中,免不了要处理各种各样的数据,最近遇到处理excel表格的问题。需求是这样的:在不改变原来excel表格样式(比如每行的宽高、表格颜色等)的情况下,添加一列新的数据。

  • 系统环境

     - OS:windows
     - python:3.6
    
  • 安装包

    pip install openpyxl
    
  • 程序

    import openpyxl
    from openpyxl.styles import Alignment
    def add_features(excel_path,sheetname):
        '''
        :param excel_path: excel表格位置
        :return:
        '''
        #特征词语
        features = ['信息', '智慧', '智能']
        #读取excel表
        excel = openpyxl.load_workbook(excel_path)
        #读取指定sheet
        sheet = excel[sheetname]
        #遍历每一行
        for i in range(2,sheet.max_row+1):
            #匹配到的词列表
            add_words = []
            #项目名称 取数据方式是在cell里传入(row_num,column_num) 即第几行第几列的元素
            project_name = sheet.cell(i,3).value
            #采购信息
            purchase_info = sheet.cell(i,13).value
    
            for word in features:
                if word in project_name or word in purchase_info:
                    add_words.append(word)
            #添加特征词
            sheet.cell(i,18).value = str(add_words)
            #设置表格 上下 水平 居中,并自动换行
            sheet.cell(i,18).alignment = Alignment(horizontal='center', vertical='center',wrap_text=True)
        #保存excel
        excel.save(excel_path)
    if __name__ == '__main__':
        add_features('test.xlsx','sheet1')
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值