将 excel 文件格式从 xls 转换为 xlsx 以在 openpyxl 中使用的可能方法



我使用openpyxl,并有一个结构动态变化的文件。我应该做一个解析器,它基于单元格值与列表元素的匹配 parencategory = [pc1, pc2...],给出单元格的坐标。但问题是我不能使用按父类别名称搜索,因为这些名称不是唯一的,而且经常在文本中。 接下来的步骤我决定按样式而不是按文本匹配关联搜索。在文件中,有关父类别的信息包含在特定颜色的合并单元格中。 我写了一个解析器,通过颜色及其属性(合并的单元格(查找我需要的单元格。 这种方式适用于 xlsx 格式。但我还需要使用旧的 xls 格式。要从xls转换为xlsx,我使用pyexcel库。

if filename.endswith('.xls'):
import pyexcel
_f, _ = filename.split('.')
pyexcel.save_book_as(file_name=file, dest_file_name=f'{_f}.xlsx')

但是,在转换时发现,样式属性的传输以某种方式被破坏,并且不可能通过颜色或合并属性接收单元格的坐标。

使用合并单元格

workbook = load_workbook(filename=file)
sheet = workbook["RFI"]
# get the list of first cell of merged cell coordinate
list_of_first_coordinate_in_merget_cell = [cell.__str__().split(':')[0] for cell in sheet.merged_cell_ranges]
for range_ in sheet.merged_cell_ranges:
# get current coordinate from all merget cell and set it as a string
cell_obj_to_str = (range_.__str__())

在这种情况下merged_cell_ranges

不起作用使用颜色

def test_excel_file_response(file):
pc_coordinate = {}
workbook = load_workbook(filename=file)
sheet = workbook["RFI"]
for row_cells in sheet.iter_rows(min_row=4):
for cell in row_cells:
if cell.value in paren_category_ and cell.fill.start_color.rgb:
pc_coordinate[cell.value] = cell.coordinate
print(cell.value, cell.fill.start_color)
return pc_coordinate

在这种情况下cell.fill.start_color不起作用

我在github上创建了关于这些主题的问题。 https://github.com/pyexcel/pyexcel/issues/206 https://github.com/pyexcel/pyexcel/issues/207

所有转换信息都基于使用 Windows 的pyexcelwin32com库(我使用的是 Ubuntu(。是否有其他转换方法适用于 Ubuntu 和 Python3.7 并在处理过程中保存样式? 欢迎任何建议或建议,因为我完全停滞不前......

嗨,如果您可以使用其他库进行以下行的转换可能会对您有所帮助。

import pandas
df = pandas.read_excel('excel.xls', sheet_name='Sheet1')
df.to_excel('output.xlsx',sheet_name='Sheet1', index=False)

如果您需要保存样式,公式,下拉列表等,请在ubuntu中使用libreoffice(soffice(。

libreoffice --convert-to xlsx my.xls --headless

我们还可以使用python中的子进程来获得所需的输出,如下所示:

subprocess.call(['libreoffice', '--headless', '--convert-to', 'xlsx', 'my.xls'])
  • 库 xlstoxlsx 保存样式,但不保存下拉列表、公式等。
  • 我们也可以在 xlrd 的帮助下进行转换,但它不会保存下拉菜单、公式等。

参考: https://stackoverflow.com/a/21531316/3177661

相关内容

最新更新