openpyxl - 使用 xlrd 将 xls 转换为 xlsx
问题描述
我正在使用下面的确切脚本(文件路径除外)尝试将 xls 转换为 xlsx。该脚本成功,但未产生任何输出。我是否缺少一些基本的东西,比如输入一些变量值或文件名,或者没有将文件正确保存为 xlsx?
import xlrd
import os
from openpyxl.workbook import Workbook
filenames = os.listdir("file_path")
for fname in filenames:
if fname.endswith(".xls"):
def cvt_xls_to_xlsx(fname):
book_xls = xlrd.open_workbook(fname)
book_xlsx = Workbook()
sheet_names = book_xls.sheet_names()
for sheet_index in range(0,len(sheet_names)):
sheet_xls = book_xls.sheet_by_name(sheet_names[sheet_index])
if sheet_index == 0:
sheet_xlsx = book_xlsx.active
sheet_xlsx.title = sheet_names[sheet_index]
else:
sheet_xlsx = book_xlsx.create_sheet(title=sheet_names[sheet_index])
for row in range(0, sheet_xls.nrows):
for col in range(0, sheet_xls.ncols):
sheet_xlsx.cell(row = row+1 , column = col+1).value = sheet_xls.cell_value(row, col)
cvt_xls_to_xlsx(fname)
book_xlsx.save(fname.xlsx)
我已经用最后两行命令更新了上面的脚本,但我现在收到以下错误消息:
文件“C:\Users\local\Documents\Tasks\Python\Excelconvert.py”,第 26 行,在 cvt_xls_to_xlsx(fname)
文件“C:\Users\local\Documents\Tasks\Python\Excelconvert.py”,第 10 行,在 cvt_xls_to_xlsx book_xls = xlrd.open_workbook(fname)
文件“C:\Users\local\Python34\lib\site-packages\xlrd__init__.py”,第 157 行,在 open_workbook ragged_rows=ragged_rows,
文件“C:\Users\local\Python34\lib\site-packages\xlrd\book.py”,第 92 行,在 open_workbook_xls biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
文件“C:\Users\local\Python34\lib\site-packages\xlrd\book.py”,第 1278 行,在 getbof bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8 ])
文件“C:\Users\local\Python34\lib\site-packages\xlrd\book.py”,第 1272 行,在 bof_error 中引发 XLRDError('不支持的格式,或损坏的文件:' + msg) xlrd.biffh.XLRDError:不支持的格式,或损坏的文件:预期的 BOF 记录;找到 b'# - 复制'
'# - 复制'是什么意思?我看到其他人建议它与文件格式有关,但通常这是一个 xml 错误,而不是我上面的错误。任何解决方案将不胜感激。
解决方案
推荐阅读
- python - Pandas DataFrame 到以元组为键和值的字典
- javascript - 如何使 javascript 代码与按钮一起使用以重新排序表行?
- sql - 如何使用一个选择的返回值到另一个选择中来对它们求和?
- wordpress - wordpress acf链接标题不显示
- c# - 为什么是 IProgress
Report(T) 方法阻塞了 UI 线程? - html - 表单发布操作转到错误的 URL
- cassandra - “drop table”命令的 Cassandra 服务器端超时配置
- php - PHP 排序降级版本从 7 到 5 结果问题
- r - 过滤数据框的每一列,将 NA 用于不匹配的值
- python - 根据语义编号在 Python 中读取文件