python 中使用openpyxl处理excel
2021/9/15 11:04:58
本文主要是介绍python 中使用openpyxl处理excel,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import openpyxl from Contens.Log import HandleLog from Contens.Config import HandleConfig do_config = HandleConfig('Config.conf') do_log = HandleLog().get_logger() do_log.debug("aaaaaaaaaaa") column1 = do_config.get_int('excel', 'column1') column2 = do_config.get_int('excel', 'column2') class HandleExcel: """ 处理excel表格类 """ def __init__(self, Filename, Sheetname=None): self.Filename = Filename self.Sheetname = Sheetname # 获取所有数据 def get_datas(self): wb = openpyxl.load_workbook(self.Filename) try: if self.Sheetname is None: ws = wb.active else: ws = wb[self.Sheetname] except Exception as a: do_log.exception('表单名字输入错误') raise a else: get_title_data = tuple(ws.iter_rows(max_row=1, values_only=True))[0] get_value_data = tuple(ws.iter_rows(min_row=2, values_only=True)) data_list = [] for value_data in get_value_data: value_dict = dict(zip(get_title_data, value_data)) data_list.append(value_dict) return data_list # 获取指定行数据 def get_specify_data(self, row): return self.get_datas()[row - 1] # 写入指定列数据 def write_datas(self, row, actual, result): write_wb = openpyxl.load_workbook(self.Filename) if self.Sheetname is None: write_ws = write_wb.active else: write_ws = write_wb[self.Sheetname] if isinstance(row, int) and (2 <= row <= write_ws.max_row): actual_cell = write_ws.cell(row=row, column=column1, value=actual) result_cell = write_ws.cell(row=row, column=column2, value=result) write_wb.save(self.Filename) else: print('行号输入错误') return '行号输入错误' pass # if __name__ == '__main__': # # c = # do_excel = HandleExcel(do_config.get_value('excel', 'filename')) # do_excel.write_datas('c', actual='a', result='b')
这篇关于python 中使用openpyxl处理excel的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型