python向excel写数据_Python-Excel-openpyxl-09-向Excel中写入数据

系统:Windows 7

语言版本:Anaconda3-4.3.0.1-Windows-x86_64

编辑器:pycharm-community-2016.3.2

openpyxl:2.6.2这个系列讲讲Python对Excel的操作

使用openpyxl模块

今天讲讲向Excel中写入信息

Part 1:示例将某文件夹下所有子文件名全部写入Excel中

文件夹

执行结果

Part 2:代码import os

from openpyxl import load_workbook

root_address = os.path.dirname(os.path.abspath(__file__))

input_folder = "TEST"

folder_address = os.path.join(root_address, input_folder)

list_file = os.listdir(folder_address)

print(list_file)

excel_name = r"openpyxl示例_9_文件清单.xlsx"

excel_address = os.path.join(root_address, excel_name)

print(excel_address)

wb = load_workbook(excel_address)

sht = wb.worksheets[0]

sht["A1"] = "序号"

sht["B1"] = "文件名"

# 清空原有信息

max_row = sht.max_row

max_col = sht.max_column

if max_row > 1 and max_col > 0:

for row in sht.iter_rows(min_row=2, min_col=1, max_col=max_col, max_row=max_row):

for cell in row:

cell.value = ""

for i, ele in enumerate(list_file):

sht.cell(row=i+2, column=1, value=i+1)

sht.cell(row=i+2, column=2, value=ele)

wb.save(excel_address)

print("ok")

代码截图

Part 3:部分代码解读for i, ele in enumerate(list_file)对列表list_file进行遍历循环,i为其索引号,ele为其元素,索引号从0开始

sht.cell(row=i+2, column=1, value=i+1)向第i+2行,第1列,写入i+1

for row in sht.iter_rows(min_row=2, min_col=1, max_col=max_col, max_row=max_row),for cell in row,对第2行到第max_row行,第1列到max_col列进行遍历

list_file = os.listdir(folder_address)获取子文件或者子文件夹名称

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值