1.需要导入两个模块:xlwt 和 xlrd3? (模块导入、安装方法自行问度娘)
2.注意:xlwt 仅支持 xls 格式
Excel 表内写入数据:
workbook? :对应excel表文件
sheet? ?:对应excel表中不同页,如excel表中左下角的sheet1、sheet2、sheet3
nrows? :sheet中对应行
ncols? ?:sheet中对应列
cell? ?:对应表内的单元格,即由行和列组成的格子
import xlwt
from datetime import datetime
style0 = xlwt.easyxf('font: name Times New Roman, color-index green, bold on',
num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='D-MMM-YY')
wb = xlwt.Workbook()
#add_sheet() 加sheet表,参数填的表名
ws = wb.add_sheet('A Test Sheet')
ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 2)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
读取Excel 表内数据:
import xlrd3 as xlrd
book = xlrd.open_workbook("example.xls")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell C3 is {0}".format(sh.cell_value(rowx=2, colx=2)))
for rx in range(sh.nrows):
print(sh.row(rx))
|