【发布时间】:2022-01-25 02:02:01
【问题描述】:
我正在尝试合并具有许多列的多个 .xls 文件,但 1 列带有超链接。我尝试使用 Python 执行此操作,但一直遇到无法解决的错误。
为了简洁起见,超链接隐藏在文本部分下。以下 ctrl-click 超链接是我在 .xls 文件中遇到的示例:ES2866911 (T3)。
为了提高重现性,我在下面添加了 .xls1 和 .xls2 示例。
xls1:
| Title | Publication_Number |
|---|---|
| P_A | ES2866911 (T3) |
| P_B | EP3887362 (A1) |
.xls2:
| Title | Publication_Number |
|---|---|
| P_C | AR118706 (A2) |
| P_D | ES2867600 (T3) |
期望的结果:
| Title | Publication_Number |
|---|---|
| P_A | ES2866911 (T3) |
| P_B | EP3887362 (A1) |
| P_C | AR118706 (A2) |
| P_D | ES2867600 (T3) |
我无法在不丢失格式或丢失超链接的情况下将 .xls 文件导入 Python。此外,我无法将 .xls 文件转换为 .xlsx。我无法获取 .xlsx 格式的 .xls 文件。下面我简要总结一下我的尝试:
1.) 使用 pandas 阅读是我的第一次尝试。很容易做到,但是PD中的所有超链接都丢失了,而且原始文件中的所有格式都丢失了。
2.) 使用 openpyxl.load 读取 .xls 文件
InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.
3.) 将 .xls 文件转换为 .xlsx
from xls2xlsx import XLS2XLSX
x2x = XLS2XLSX(input.file.xls)
wb = x2x.to_xlsx()
x2x.to_xlsx('output_file.xlsx')
TypeError: got invalid input value of type <class 'xml.etree.ElementTree.Element'>, expected string or Element
import pyexcel as p
p.save_book_as(file_name=input_file.xls, dest_file_name=export_file.xlsx)
TypeError: got invalid input value of type <class 'xml.etree.ElementTree.Element'>, expected string or Element
During handling of the above exception, another exception occurred:
StopIteration
4.) 例如,即使我们能够使用 xlrd 读取 .xls 文件(这意味着我们永远无法将文件另存为 .xlsx,我什至看不到超链接:
import xlrd
wb = xlrd.open_workbook(file) # where vis.xls is your test file
ws = wb.sheet_by_name('Sheet1')
ws.cell(5, 1).value
'AR118706 (A2)' #Which is the name, not hyperlink
5.) 我尝试安装旧版本的 openpyxl==3.0.1 以克服类型错误,但没有成功。我尝试使用带有 xlrd 引擎的 openpyxl 打开 .xls 文件,出现类似的 typerror “xml.entree.elementtree.element”错误。我尝试了很多方法将 .xls 文件批量转换为 .xlsx,但都出现了类似的错误。
显然我可以用 excel 打开并另存为 .xlsx 但这违背了整个目的,而且我不能为 100 个文件这样做。
【问题讨论】:
-
我会重温熊猫。它允许您在“引擎”之间切换:
xlrd可以读取较旧的 .xls 文件,openpyxl可以写入较新的 .xlsx 文件。 read_excel 还有一个方便的skiprows参数:pandas.pydata.org/docs/reference/api/pandas.read_excel.html 另外请确保您拥有最新版本的 pandas,因为它一直在扩展。
标签: python excel pandas openpyxl xlsx