python简单操作excel

# -*- coding: utf-8 -*-

# ## pip install xlrd
# 导入xlrd模块
import xlrd

# 打开excel文件,获取文件对象
efile = xlrd.open_workbook(r"C:\Users\Administrator\Desktop\ip地址信息表.xlsx")

# 获取所有sheet    对象.sheet_names()
# 获取sheet的数量  对象.nsheets
# 获取所有sheet对象  对象.sheets()
# 通过sheet名查找   对象.sheet_by_name('test')
# 通过索引查找      对象.sheet_by_index(3)
# print(efile.sheet_names())
sheetfile = efile.sheet_by_name('Sheet1')
# 获取总行数
# print(sheetfile.nrows)
# 获取总列数
# print(sheetfile.ncols)
# 获取当前sheet名
# print(sheetfile.name)
# 获取第一行所有内容,以列表的方式展示
print(sheetfile.row_values(0))

# 遍历此表格的所有列,取出列中对应的元素
for i in range(1, sheetfile.ncols):
    print(sheetfile.row_values(i)[4])
    print(sheetfile.row_values(i)[3])
    print(int(sheetfile.row_values(i)[2]))
    print(sheetfile.row_values(i)[1])
    print(sheetfile.row_values(i)[0])

# -*- coding: utf-8 -*-

# ## pip install openpyxl
import datetime
import time

from openpyxl import Workbook

# 创建文件对象
wb = Workbook()

# 获取第一个sheet
ws = wb.active

# 写入数字(A字段1为记录)
ws['A1'] = 42
# 写入中文
ws['B1'] = '你好' + 'automation test'
# 写入多个单元格
ws.append([1, 2, 3])

# 写入当前时间
ws['A2'] = datetime.datetime.now()
# 写入一个自定义的时间格式
# ###注:这里回报一个错UnicodeEncodeError,原因是不能在strftime中写入中文字符,所有要用字符串格式化加入
ws['A3'] = time.strftime("%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}").format(y="年", m="月", d="日", h="时", f="分", s="秒")

# 保存文件(保存文件为文件对象.save()括号里传入保存路径)
wb.save(r"C:\Users\Administrator\Desktop\test1.xlsx")
发布了45 篇原创文章 · 获赞 9 · 访问量 2265

猜你喜欢

转载自blog.csdn.net/adsszl_no_one/article/details/103548856