如何将xls转换为xlsx [英] how to convert xls to xlsx

查看:215
本文介绍了如何将xls转换为xlsx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些* .xls(excel 2003)文件,我想将这些文件转换为xlsx(excel 2007)。



我使用uno python包当我保存文件时,
我可以设置过滤器名称:MS Excel 97
但是没有像'MS Excel 2007'的过滤器名称,



请帮助我,如何设置过滤器名称将xls转换为xlsx?

解决方案

我不得不这样做。主要思想是使用 xlrd 模块来打开和解析一个xls文件,并使用 openpyxl
内容写入 xlsx strong>模块。



这是我的代码。 注意! 它不能处理复杂的xls文件,如果要使用,您应该添加自己的解析逻辑。



来自openpyxl.workbook导入工作簿
从openpyxl.reader.excel导入load_workbook,InvalidFileException

def open_xls_as_xlsx(filename)

 
#首先打开使用xlrd
book = xlrd.open_workbook(filename)
index = 0
nrows,ncols = 0,0
,而nrows * ncols = = 0:
sheet = book.sheet_by_index(index)
nrows = sheet.nrows
ncols = sheet.ncols
index + = 1

#准备一个xlsx工作表
book1 = Workbook()
sheet1 = book1.get_active_sheet()

for xrange(0,nrows):
for col in xrange (0,ncols):
sheet1.cell(row = row,column = col).value = sheet.cell_value(row,col)

返回book1


I have some *.xls(excel 2003) files, and I want to convert those files into xlsx(excel 2007).

I use the uno python package, when I save the documents, I can set the Filter name: MS Excel 97 But there is no Filter name like 'MS Excel 2007',

please help me, how can set the the filter name to convert xls to xlsx ?

解决方案

I've had to do this before. The main idea is to use the xlrd module to open and parse a xls file and write the content to a xlsx file using the openpyxl module.

Here's my code. Attention! It cannot handle complex xls files, you should add you own parsing logic if you are going to use it.

import xlrd
from openpyxl.workbook import Workbook
from openpyxl.reader.excel import load_workbook, InvalidFileException

def open_xls_as_xlsx(filename):
    # first open using xlrd
    book = xlrd.open_workbook(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.get_active_sheet()

    for row in xrange(0, nrows):
        for col in xrange(0, ncols):
            sheet1.cell(row=row, column=col).value = sheet.cell_value(row, col)

    return book1

这篇关于如何将xls转换为xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆