1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xlrd
import xlwt
def read_excel():
file_name = 'demo.xlsx'
# 打开excel文件
wb = xlrd.open_workbook(file_name)
# 获取所有表格名字
print(wb.sheet_names())
# 通过索引获取表格
sheet1 = wb.sheet_by_index(0)
print(sheet1.name, sheet1.nrows, sheet1.ncols)
# 获取行内容
rows = sheet1.row_values(2)
print(rows)
# 获取列内容
cols = sheet1.col_values(3)
print(cols)
# 获取表格里的内容,三种方式
print(sheet1.cell(1, 0).value)
print(sheet1.cell_value(1, 0))
print(sheet1.row(1)[0].value)
def write_excel():
f = xlwt.Workbook()
# 添加sheet
sheet1 = f.add_sheet('Students', True)
# 创建杭数据和列数据
row0 = ["qq", "ddd", "fgg", "hjj"]
column0 = ["zsfsd", "ghg", "Python", "fs", "fgsf", "zbg"]
# 写第一行
for i in range(0, len(row0)):
sheet1.write(0, i, row0[i])
# 写第一列
for i in range(0, len(column0)):
sheet1.write(i + 1, 0, column0[i])
# 保存文件为xls格式,xlsx格式不能打开
f.save('test.xls')
|