一 函数功能
1 本文实现了打开 txt、word、excel 格式文件
2 读取文件内容
3 并打印到text.Browser上
二 源码
import docx
from xlrd import open_workbook
@pyqtSlot()
def on_menu_files_open_triggered(self):
## win32com 对Python3.x 支持效果不好,弃用之
# from win32com import client as wc
# word = wc.Dispatch('Word.Application')
# word.Visible = 0
print("打开")
dialog = QFileDialog()
my_file_path = dialog.getOpenFileName(self, "打开文件",
"E:\\7Program\\Pycharm\\PyQt\\eric6-19.03\\Workspace\\")[0]
print(my_file_path)
if my_file_path[-4:] == '.doc' or my_file_path[-5:] == '.docx':
# my_worddoc = word.Documents.Open(my_file_path.replace('/', '\\'))
# print(type(my_worddoc))
# my_count = my_worddoc.Paragraph.Count
# for i in range(my_count):
# my_pr = my_worddoc.paragraph[i].Range
# print(my_pr.text)
# self.textBrowser.append(my_pr.text)
# my_worddoc.Close()
## 采用 python-docx
# my_doc = docx.Document(my_file_path.replace('/', '\\'))
# # print(my_doc.paragraphs[0].text)
# for my_paragraph in my_doc.paragraphs:
# print(my_paragraph.text)
# self.textBrowser.append(my_paragraph.text)
self.textBrowser.append(read_docx(my_file_path.replace('/', '\\')))
elif my_file_path.endswith('.xlsx'):
print('excel!')
wb = open_workbook(my_file_path.replace('/', '\\'))
for s in wb.sheets():
for row in range(s.nrows):
for col in range(s.ncols):
print(s.cell(row, col).value)
elif my_file_path[-4:] == '.txt':
f = open(my_file_path[0], 'r', encoding="utf-8")
my_data = f.read()
f.close()
self.textBrowser.append(my_data)
else:
QMessageBox.information(self, 'Information', '不支持的文件格式')
三 注意事项
1 win32com 对Python3.x 支持效果不好
建议使用python-docx、xlrd、xlwt 第三方库
2 encoding
3 path "/" 转义
4 cell 类的用法
5 具体可以参考官方库文档
下面是三木小小推的二维码,欢迎订阅呦~~
你点的每个好看,我都认真当成了喜欢
文章转载自三木小小推,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。






