首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python-Excel-openpyxl-09-向Excel中写入数据

系统:Windows 7 语言版本:Anaconda3-4.3.0.1-Windows-x86_64 编辑器:pycharm-community-2016.3.2 openpyxl:2.6.2

  • 这个系列讲讲PythonExcel的操作
  • 使用openpyxl模块
  • 今天讲讲向Excel中写入信息

Part 1:示例

  1. 将某文件夹下所有子文件名全部写入Excel

文件夹

执行结果

Part 2:代码

代码语言:javascript
复制
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:部分代码解读

  1. for i, ele in enumerate(list_file)对列表list_file进行遍历循环,i为其索引号,ele为其元素,索引号从0开始
  2. sht.cell(row=i+2, column=1, value=i+1)向第i+2行,第1列,写入i+1
  3. 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列进行遍历
  4. list_file = os.listdir(folder_address)获取子文件或者子文件夹名称
下一篇
举报
领券