openpyxl计算某一列有多少个单元格

wokaoyan1981 2020-09-05 08:48:55
一、题目:已有一个名为fromtxt.xlsx的文件,A列有4行文字,B列有1行文字,C行有4行文字,见图1所示。运用openpyxl库编写一个程序,读取电子表格,将列A中的单元格写入一个文本文件,命名为1.txt;将列B中的单元格写入另一个文本文件2.txt,以此类推。
图1 xlsx文件

二、我的解决方案:
#! /usr/bin/env python3
# P12_13_5.py - read data from 'fromtxt.xlsx' and wrtie them into several .txt files.

import openpyxl
from openpyxl.utils import get_column_letter

# read contents from 'fromtxt.xlsx'
wb = openpyxl.load_workbook('fromtxt.xlsx')
sheet = wb.active

column_num = sheet.max_column
for i in range(1, column_num+1):
file = open(str(i)+'.txt', 'w')
for j in range(1, len(sheet[get_column_letter(i)])+1):
print(sheet.cell(row=j,column=i).value)
file.write(sheet.cell(row=j,column=i).value)
file.close()

三、存在问题:读完第一列文本并写入1.xlsx后,不能正确读出第二列的单元格个数(即1个)。
系统指出16行的错误:TypeError: write() argument must be str, not None
请问如何修改,能够正确读出每一列的单元格个数?

...全文
721 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wokaoyan1981 2020-09-07
  • 打赏
  • 举报
回复
引用 2 楼 慕飒潇湘 的回复:
用xlrd吧,按照行来读,每行数据属于一个列表,对于没有数据的列表中只是一个空的占位符“”,这样你就可以按每个列表中取索引值(就是列了),判断是否非空则就插入到txt中,逻辑还是非常简单的
好的,谢谢!上面的解决思路跟你的一样。
weixin_45903952 2020-09-07
  • 打赏
  • 举报
回复
好像也可以判断一下一列有多少行,然后再循环吧
慕飒潇湘 2020-09-07
  • 打赏
  • 举报
回复
用xlrd吧,按照行来读,每行数据属于一个列表,对于没有数据的列表中只是一个空的占位符“”,这样你就可以按每个列表中取索引值(就是列了),判断是否非空则就插入到txt中,逻辑还是非常简单的
wokaoyan1981 2020-09-05
  • 打赏
  • 举报
回复
内循环里面加一个比较(==None),是则break。
#! /usr/bin/env python3
# P12_13_5.py - read data from 'fromtxt.xlsx' and wrtie them into several .txt files.

import openpyxl
from openpyxl.utils import get_column_letter

# read contents from 'fromtxt.xlsx'
wb = openpyxl.load_workbook('fromtxt.xlsx')
sheet = wb.active

column_num = sheet.max_column
for i in range(1, column_num+1):
file = open(str(i)+'.txt', 'w')
for cell in sheet[get_column_letter(i)]:
if cell.value == None:
break
else:
file.write(cell.value)
file.close()

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧