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

一、题目:已有一个名为fromtxt.xlsx的文件,A列有4行文字,B列有1行文字,C行有4行文字,见图1所示。运用openpyxl库编写一个程序,读取电子表格,将列A中的单元格写入一个文本文件,命名为1.txt;将列B中的单元格写入另一个文本文件2.txt,以此类推。
图1 xlsx文件
openpyxl计算某一列有多少个单元格
二、我的解决方案:

#! /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
请问如何修改,能够正确读出每一列的单元格个数?


回答:

#! /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()

以上是 openpyxl计算某一列有多少个单元格 的全部内容, 来源链接: utcz.com/p/937870.html

回到顶部