Python——提取excel指定单元格的数据到txt中2.将excel中指定单元格的数据提取并存储到txt⽂件中
(1)使⽤openpyxl的load_workbook模块
问题:load_workbook只能使⽤.xlsx⽂件,不能打开.xls⽂件。⽽xlrd可以打开.xlsx⽂件
.xlsx使⽤于2003版以上的excel⽂件;
.xls适⽤于2003以下的excel⽂件。
对xlrd模块的介绍( )
(2)存储为txt⽂档时的三种⽅式
读模式('r')、写模式('w')、追加模式('a')
(3)正确创建⼀个list
col1 = []、col1 = [0]*22
(4)对excel中单元格的操作⽅式
for index,item in enumerate(sh["C2":"X2"]):
j = 0
if index > 0:
print("\n")
for i in item:
print(i.value,end="")
col1[j] = i.value
j = j+1
(5)python保留⼩数点后四位数字的三种⽅法
1print(Decimal('cell.value').quantize(Decimal('0.0000')),end="") #使⽤decimal函数将⼩数点后保留四位
2print('%.4f' %cell.value,end="") #⼩数点后保留四位
3  round(cell.value,4) #⼩数点后保留四位
(6)
TypeError: 'int' object is not iterable
经过多次查询,最终到原因:不能直接⽤int进⾏迭代,⽽必须加个range。int不能使⽤迭代器函数iter( )
1错误:n=22;for i in n:
2正确:n=22;  for i in range(n):
(7)
ValueError : I/O operation on closed file. #在关闭的⽂件中进⾏I/O处理
问题:python的严格缩进,强制可读性
1错误:
2 with open("C:\Users\Desktop\matlab\","a+") as wr:
3for j in range(n):
4print(str(col1[j])+','+str(col2[j])+';')
5        wr.write(str(col1[j])+','+str(col2[j])+';')
6正确:
7 with open("C:\Users\Desktop\matlab\","a+") as wr:
8for j in range(n):
9print(str(col1[j])+','+str(col2[j])+';')
python怎么读取excel某一列10                wr.write(str(col1[j])+','+str(col2[j])+';')
(8)
1 TypeError: unsupported operand type(s) for +: 'str'and'int'
2问题:
3错误: wr.write(col1[j]+','+col2[j]+';')
4正确: wr.write(str(col1[j])+','+str(col2[j])+';')
(9)
IndexError: list assignment index out of range
问题:刚开始时定义list范围过⼩,定义的l是⼀个空list,之后却要引⽤⼀个l[j]
错误:l = [0]; l[j] = i.value
正确:l = [0]*22; l[i] = i.value;
python代码:
1from openpyxl import load_workbook
2from decimal import *
3import xlrd
4
5#df = xlrd.open_workbook(r"桌⾯\1.xlsx") #python中的‘\’表⽰转义字符,可在前⾯加上r或者使⽤‘/’
6 wb = load_workbook(r"C:\Users\Desktop\matlab\b.xlsx")
7 sh = wb["b"]
8 with open("C:\Users\Desktop\","a+") as wr:
9#names = df.sheet_names() #获取Sheet列表名,xlrd模块中专⽤
10#print(names)
11
12    col1 = [0] *22
13    col2 = [0] *22 #创建⼀个⼤⼩为22的list,python中list相当于数组
14    n=22
15
16for index,item in enumerate(sh["C2":"X2"]):
17        j = 0
18if index > 0:
19print("\n")
20for i in item:
21print(i.value,end="")
22            col1[j] = i.value
23            j = j+1
24for index,item in enumerate(sh["C5":"X5"]):
25        j = 0
26if index >0:
27print("\n")
28for cell in item:
29#print(Decimal('cell.value').quantize(Decimal('0.0000')),end=" ") #使⽤decimal函数将⼩数点后保留四位30print('%.4f' %cell.value,end="") #⼩数点后保留四位
31            col2[j] = round(cell.value,4) #⼩数点后保留四位
32            j = j+1
33
34        j = 0
35for j in range(n):
36print(str(col1[j])+','+str(col2[j])+';')
37        wr.write(str(col1[j])+','+str(col2[j])+';')

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。