在没有 win32com 的情况下将 xls 转换为 xlsx
Convert xls to xlsx without win32com
您需要在没有 win32com 的主机上将 xls 转换为 xlsx。我试过这段代码:
import xlrd, os
from openpyxl.workbook import Workbook
def open_xls_as_xlsx(filename):
# first open using xlrd
book = xlrd.open_workbook( filename =filename)
index = 0
nrows, ncols = 0, 0
while nrows * ncols == 0:
sheet = book.sheet_by_index(index)
nrows = sheet.nrows
ncols = sheet.ncols
index += 1
# prepare a xlsx sheet
book1 = Workbook()
sheet1 = book1.active()
for row in range(1, nrows):
for col in range(1, ncols):
sheet1.cell(row=row, column=col).value = sheet.cell_value(row, col)
return book1
open_xls_as_xlsx(os.getcwd() + '/Расписание_1-4_курсов_с_01.04_по_05.07.2021_(2_поток).xls').save(filename = 'path_to_file.xlsx')
但出现错误:
'Worksheet' object is not callable
或者我可以做点别的吗?请帮忙
active后不能有()。
sheet1 = book1.active
此外,2d for 循环中存在错误。
xlrd 的坐标从 0 开始,而 openpyxl 的坐标从 1 开始。
for row in range(0, nrows):
for col in range(0, ncols):
print(sheet.cell_value(row,col))
sheet1.cell(row=row+1, column=col+1).value = sheet.cell_value(row, col)
您需要在没有 win32com 的主机上将 xls 转换为 xlsx。我试过这段代码:
import xlrd, os
from openpyxl.workbook import Workbook
def open_xls_as_xlsx(filename):
# first open using xlrd
book = xlrd.open_workbook( filename =filename)
index = 0
nrows, ncols = 0, 0
while nrows * ncols == 0:
sheet = book.sheet_by_index(index)
nrows = sheet.nrows
ncols = sheet.ncols
index += 1
# prepare a xlsx sheet
book1 = Workbook()
sheet1 = book1.active()
for row in range(1, nrows):
for col in range(1, ncols):
sheet1.cell(row=row, column=col).value = sheet.cell_value(row, col)
return book1
open_xls_as_xlsx(os.getcwd() + '/Расписание_1-4_курсов_с_01.04_по_05.07.2021_(2_поток).xls').save(filename = 'path_to_file.xlsx')
但出现错误:
'Worksheet' object is not callable
或者我可以做点别的吗?请帮忙
active后不能有()。
sheet1 = book1.active
此外,2d for 循环中存在错误。 xlrd 的坐标从 0 开始,而 openpyxl 的坐标从 1 开始。
for row in range(0, nrows):
for col in range(0, ncols):
print(sheet.cell_value(row,col))
sheet1.cell(row=row+1, column=col+1).value = sheet.cell_value(row, col)