一、題目:已有一個名為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
請問如何修改,能夠正確讀出每一列的單元格個數?
uj5u.com熱心網友回復:
內回圈里面加一個比較(==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()
uj5u.com熱心網友回復:
用xlrd吧,按照行來讀,每行資料屬于一個串列,對于沒有資料的串列中只是一個空的占位符“”,這樣你就可以按每個串列中取索引值(就是列了),判斷是否非空則就插入到txt中,邏輯還是非常簡單的uj5u.com熱心網友回復:
好像也可以判斷一下一列有多少行,然后再回圈吧uj5u.com熱心網友回復:
好的,謝謝!上面的解決思路跟你的一樣。轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/8701.html
