-
背景介绍
在实际工作中,免不了要处理各种各样的数据,最近遇到处理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')
不改变原excel格式添加新数据
最新推荐文章于 2025-04-29 15:28:57 发布