python版excel题库转文本txt和word
本帖最后由 ghostlg 于 2021-9-22 18:16 编辑之前易语言版本 https://www.52pojie.cn/thread-1472488-1-1.html
之前用易语言写的工具,最近学习python又写了个python的excel转word或txt和json
import json
import xlwings as xw
import docx
app = xw.App()# 新打开一个进程
# 禁用提示和屏幕刷新可以提升速度,操作完成后记得设置为True
app.display_alerts = False
app.screen_updating = False
#路径前边加r表示绝对路径
path = r"自己的excel.xls"
# #打开已有excel
app = xw.App(visible=False, add_book=False)
wb = app.books.open(path)
sheet = wb.sheets[0]
# 通过last_cell方式获取最下边且最右边的一个单元格。
last_cell = sheet.used_range.last_cell
last_row = last_cell.row
last_col = last_cell.column
data = []
for i in range(last_row):
dict1 = {}
list1 = []
for j in range(last_col):
str1 = chr(65+j)
str2 =str(i+1)
cell = wb.sheets["sheet1"].range(str1+str2).value
list1.append(cell)
for n in range(6):
dict1 =list1
data.append(dict1)
wb.close()
app.quit()
# 写入 JSON 数据
def writeTojson(data):
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取数据
def readjson(ptah):
with open(ptah, 'r') as f:
data = json.load(f)
# print(data)
return data
writeTojson(data)
data = readjson(r"自己的.json")
# 写入txt
str=""
for i in range(len(data)):
dict2 = {}
dict2 = data
for key in dict2:
str = str + "\n" + dict2
with open("test.txt","w") as f:
f.write(str)
# 写入word
doc = docx.Document()
doc.add_paragraph(str)
doc.save('test.docx') import json
import xlwings as xw
import docx
app = xw.App()# 新打开一个进程
# 禁用提示和屏幕刷新可以提升速度,操作完成后记得设置为True
app.display_alerts = False
app.screen_updating = False
#路径前边加r表示绝对路径
path = r"自己的excel.xls"
# #打开已有excel
app = xw.App(visible=False, add_book=False)
wb = app.books.open(path)
sheet = wb.sheets
# 通过last_cell方式获取最下边且最右边的一个单元格。
last_cell = sheet.used_range.last_cell
last_row = last_cell.row
last_col = last_cell.column
data = []
for i in range(last_row):
dict1 = {}
list1 = []
for j in range(last_col):
str1 = chr(65+j)
str2 =str(i+1)
cell = wb.sheets["sheet1"].range(str1+str2).value
list1.append(cell)
for n in range(6):
dict1 =list1
data.append(dict1)
wb.close()
app.quit()
# 写入 JSON 数据
def writeTojson(data):
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取数据
def readjson(ptah):
with open(ptah, 'r') as f:
data = json.load(f)
# print(data)
return data
writeTojson(data)
data = readjson(r"自己的.json")
# 写入txt
str=""
for i in range(len(data)):
dict2 = {}
dict2 = data
for key in dict2:
str = str + "\n" + dict2
with open("test.txt","w") as f:
f.write(str)
# 写入word
doc = docx.Document()
doc.add_paragraph(str)
doc.save('test.docx') 沙发好评,方便复制 谢谢大佬分享 谢谢楼主分享! 刚好需要
页:
[1]