Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#! /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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...