首页 > 技术文章 > 【python 3.6】xlwt和xlrd对excel的读写操作

BH8ANK 2018-05-15 20:37 原文

 

 

#python 3.6
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'BH8ANK'


import xlrd


'''=================xlrd负责读取excel,功能上只能读===============================================
'''

myfile = xlrd.open_workbook(r'D:\python_test\cc.xlsx')#打开excel
sheets = myfile.sheet_names()#读取sheet名
print(sheets)



'''注意,参数首位为0
'''
first_table = myfile.sheet_by_index(0)#打开第0个sheet
print(first_table.name)#返回sheet名
print(first_table.nrows)#返回sheet行数
print(first_table.ncols)#返回sheet列数

#返回第一行
first_row = first_table.row_values(0)
print(first_row)

#返回第一列
first_col = first_table.col_values(0)
print(first_col)

#返回指定单元格,第10行,第1列
target = first_table.cell(10,1).value
print(target)


'''=================xlwt负责写入excel,功能上只能写===============================================
'''
import xlwt
import datetime

font0 = xlwt.Font()
font0.name = 'TimesNewRoman'
font0.colour_index = 2
font0.bold = True

style0 = xlwt.XFStyle()
style0.font = font0

style1 = xlwt.XFStyle()
style1.num_format_str = 'D-MMM-YY'

wb = xlwt.Workbook()
ws = wb.add_sheet('ATestSheet')

ws.write(0, 0, 'Test', style0)
ws.write(1, 0, 'BH8ANK', style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save(r'D:\python_test\dd.xlsx')

 

推荐阅读