1. xlsx读取excel
xlrd 必须为1.2.0或之前版本, 其他版本只能支持xls
import xlrd
import xlwt
def read_excel():
# 打开文件
workBook = xlrd.open_workbook('data/HanXueLi_201801.xlsx');
# 1.获取sheet的名字
# 1.1 获取所有sheet的名字(list类型)
allSheetNames = workBook.sheet_names()
print(allSheetNames);
# 1.2 按索引号获取sheet的名字(string类型)
sheet1Name = workBook.sheet_names()[0]
print(sheet1Name)
# 2. 获取sheet内容
## 2.1 法1:按索引号获取sheet内容
sheet1_content1 = workBook.sheet_by_index(0) # sheet索引从0开始
## 2.2 法2:按sheet名字获取sheet内容
sheet1_content2 = workBook.sheet_by_name('Sheet1')
# 3. sheet的名称,行数,列数
print(sheet1_content1.name,sheet1_content1.nrows,sheet1_content1.ncols)
# 4. 获取整行和整列的值(数组)
rows = sheet1_content1.row_values(3) # 获取第四行内容
cols = sheet1_content1.col_values(2) # 获取第三列内容
print(rows)
# 5. 获取单元格内容(三种方式)
print(sheet1_content1.cell(1, 0).value)
print(sheet1_content1.cell_value(2, 2))
print(sheet1_content1.row(2)[2].value)
# 6. 获取单元格内容的数据类型
# Tips: python读取excel中单元格的内容返回的有5种类型 [0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error]
print(sheet1_content1.cell(1, 0).ctype)
if __name__ == '__main__':
read_excel()
2.lxwt 写入excel
import lxwt
# 新建一个excel文件
file = xlwt.Workbook() # 注意这里的Workbook首字母是大写
# 新建一个sheet,这里是新建excel工作表,如果数据循环写入一定不要把这行代码写入循环之内,不然会只写入最后一个数据,切记。
table = file.add_sheet('sheet name')
# 写入数据table.write(行,列,value)
table.write(0,0,'test')# 循环写入,直接循环这三个数字就可以了(行、列、数据)
# 如果对一个单元格重复操作,会引发下面错误。
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
# 所以在打开时加cell_overwrite_ok=True 解决
table = file.add_sheet('sheet name',cell_overwrite_ok=True )
file.save('demo.xls') # 保存文件,保存该excel文件,有同名文件时直接覆盖
到此数据就能写入excel中了,下面在介绍一些其他操作。
使用style
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() #为样式创建字体
font.name = 'Times New Roman'
font.bold = True
style.font = font #为样式设置字体
table.write(0, 0, 'some bold Times text', style) # 使用样式
xlwt 允许单元格或者整行地设置格式。还可以添加链接以及公式。可以阅读源代码,那里有例子:
dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.
# 例子
import xlwt
# 指定file以utf-8的格式打开
file = xlwt.Workbook(encoding='utf-8')
# 指定打开的文件名
table = file.add_sheet('Sheet 1', cell_overwrite_ok=True)
info_list = [
['张三', '150', '120', '100'],
['李四', '90', '99', '95'],
['王五', '60', '66', '68'],
]
for i, p in enumerate(info_list):
# 将数据写入文件,i是enumerate()函数返回的序号数
for j, q in enumerate(p):
# print(i, j, q)
table.write(i, j, q)
file.save('data.xls')
3. csv 写入
# coding:utf-8
import csv
file = open('test.csv','w',encoding='utf-8',newline="") #newline="",可避免csv里有空行出现
writerObj = csv.writer(file)
writerObj.writerow(['title', 'content'])
file.close()
4. csv 读取
# coding:utf-8
import csv
f = csv.reader(open('1111.csv','r'))
for i in f:
print(i)