openpyxl一点心得
先上代码
from openpyxl import workbook,load_workbook class HomeWork(): def creat_xlsx(self): """ 创建excel文件在当前目录 :return: """ wb = workbook.Workbook() ws = wb.active ws.title = "homework_sheet" list = ("床前明月光","疑是地上霜","举头望明月","低头思故乡") for i in range(1,5): ws.cell(1,i).value = list[i-1] list1 = ("锄禾日当午","汗滴禾下土","谁知盘中餐","粒粒皆辛苦") for i in range(1,5): ws.cell(2,i).value = list1[i-1] wb.save("HomeWork.xlsx") wb.close() def read_xlsx(self,xlsx = "HomeWork.xlsx",ws = "homework_sheet"): """ 读取excel文件中数据并整理成列表返回 :param xlsx: :param ws: :return: """ wb = load_workbook(xlsx) ws = wb.get_sheet_by_name(ws) list = [] list1 = [] for i in range(1,ws.max_row+1): for j in range(1,ws.max_column+1): str = ws.cell(i,j).value list.append(str) list1.append(list.copy()) list.clear() wb.close() return list1 def edit_xlsx(self,xlsx_row = None,xlsx_column= None,xlsx_str= None,xlsx = "HomeWork.xlsx",ws = "homework_sheet"): """ 在指定位置写入数据 :param xlsx: :param ws: :return: """ wb = load_workbook(xlsx) ws = wb.get_sheet_by_name(ws) ws.cell(xlsx_row,xlsx_column).value = xlsx_str wb.save(xlsx) wb.close() if __name__ == "__main__": homework = HomeWork() # 创建文件 homework.creat_xlsx() # 读取文件并整理 read_list = homework.read_xlsx() print(read_list) #写入 i = int(input("请输入你要编辑的行数:")) j = int(input("请输入你要编辑的列数:")) str = input("请输入你要替换的数据:") homework.edit_xlsx(i,j,str)
从创建到读写都涉及到的三组方法,相关的用法百度很多,就不一一说明了。
注意点三处:
1.文件创建/读/写的最后都不要忘记save和close,不然很可能吃力不讨好
2.出现Permission denied报错不要慌张,如果是windows平台,第一时间查看文件是否手动打开了,然后查看写入的数据格式是否正确;如果是linux平台或者类似平台,可以手动赋予权限
3.打开/创建的文件名需要带后缀,并且后缀一定要是xlsx,不然会出现文件无法识别的报错
4.如果不是汉字而是输出其他类型内容,比如字典、列表或者元祖,可以使用eval(str)来转换