首页 新闻 会员 周边 捐助

如何用openpyxl读取表格内容,再将获取的内容保存为.txt文件

0
悬赏园豆:20 [待解决问题]

我在使用load_workbook()读取excel获取内容后,再将内容保存为txt文件时遇到下面这栏报错
File "D:/python/excel_py.py", line 58, in sdx
yr = open('C:\iyb\ty.txt', 'w',
TypeError: load_workbook() got an unexpected keyword argument 'encoding'

代码如下

-- coding: utf-8 --

from openpyxl import *
from openpyxl.utils import get_column_letter, column_index_from_string

def excel_cellname():
wb = load_workbook('C:/Users/USER/Desktop/20210709.xlsx')
ws = wb.active
maxRow = ws.max_row # 获取最大行数
maxColumn = ws.max_column # 获取最大列数
# print(ws['B3'].value)
# print(maxRow, range(maxColumn))
data_hang = []
char = []
charrow = []
if maxRow > 2 and maxColumn > 2:
for i in range(maxRow):
for j in range(maxColumn):
try:
if ws.cell(i, j).value != None:
char.append(j)
# print(ws.cell(i,j).value)
if ws.cell(i, j).value == "jk" and ws.cell(i, j + 1).value != None:
# print(i, j)
# print(ws.cell(i, j))
charrow.append(i)
data_hang.append(ws.cell(i, j + 2).value.replace("\n", ""))
except:
pass

                # continue
# print(data_hang)
print(charrow)
print(get_column_letter(max(char)))
print(get_column_letter(min(char) + 1))
Cellmin = get_column_letter(min(char) + 1)
Cellmax = get_column_letter(max(char))
# print(ws["A1:D10"])
charname = []
for cr in charrow:
    # print(ws['B' + str(cr) + ':' + 'G' + str(cr)])
    for sw in ws[Cellmin + str(cr) + ':' + Cellmax + str(cr)]:
        for wf in sw:
            if wf.value != None:
                # print(wf.value.replace("\n", ""))
                charname.append(wf.value.replace("\n", ""))
sdd = "\n".join(charname)
er = sdd.replace("\n", "")
qe = er.replace(" ", "")
return qe

def sdx():
xc = excel_cellname()
print(xc)
yr = open('C:\iyb\ty.txt', 'w',
encoding='UTF-8')
yr.write(xc)
yr.flush()
sdx()

Faizel_Chen的主页 Faizel_Chen | 初学一级 | 园豆:18
提问于:2021-07-11 16:07
< >
分享
所有回答(2)
0

报错信息里面说的好像是load_workbook得到了一个不应该得到的参数encoding,检查一下你的代码把

编程小大白 | 园豆:530 (小虾三级) | 2021-07-12 08:19
0

由于我是新手,看你的代码比较费劲,但是我根据你的标题写了一段代码,你看看能不能拿去改改。

代码如下:

wb = load_workbook(r'simple_data.xlsx')
ws = wb.active

with open('1.txt', mode='w') as f:
    for row in ws:
        for cell in row:
            f.write(f'{cell.value},')
        f.write('\n')
DoVepAn | 园豆:204 (菜鸟二级) | 2022-03-12 14:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册