Python_操作excel(openpyxl)
1.安装模块
pip install openpyxl
2.读取
import openpyxl def main(): # 打开工作簿 wb = openpyxl.load_workbook('qqq.xlsx') # 获取表单 sh = wb['Sheet1'] # 按行读取 rows = sh.rows # 循环每行 for row in list(rows): # 循环每列 for i in row: # 打印每个格子的值 print(i.value) if __name__ == '__main__': main()
3.写入
import openpyxl workbook = openpyxl.Workbook() sheet = workbook.active sheet.title = 'Sheet1' file_name = "wdc.txt" set_title = True with open(file_name, 'r') as file: lines = file.readlines() x = 1 for line in lines: field_list = line.split(",") if set_title: y = 1 for field in field_list: sheet.cell(row=x, column=y, value=field.split(":")[0]) y += 1 x += 1 set_title = False y = 1 for field in field_list: sheet.cell(row=x, column=y, value=field.split(":")[-1]) y += 1 x += 1 workbook.save('new.xlsx')