python怎么保存xlsx不损坏,python将excel xlsx转换(读取并保存)为xlsx

How can I convert an existing xlsx Excel file into xls while retaining my Excel file formatting? I use Anaconda Python 3, so I'm not sure I can use xlutils... I was not able to install it via conda install xlutils because of lots of incompatibilities. So now I use this code without the xlutils.copy():

import xlrd, xlwt

wb = xlrd.open_workbook(my_xlsx_excel_file)

# wb = xlutils.copy(wb)

wb.save(my_xlsx_excel_file[:-1])

And I get this error:

AttributeError: 'Book' object has no attribute 'save'

Thank you!

解决方案

First things first: Why do you want to convert to .xls? This is usually a sign that you are using outdated tools somewhere in the process, and it might be better to use newer tools rather than convert the data to an older format.

But, if you really need to convert to .xls while preserving formatting, your only realistic choice at this time is to use Excel itself. You didn't say which platform you are using, but if it's Windows or Mac, and you have Excel installed, then the most straightforward way to automate Excel is probably xlwings. In principle this will allow you to use Python to open the .xlsx file in Excel (an actual, running instance of Microsoft Excel) and do "save as" to a .xls file.

I say "in principle" because I don't personally know how to do it in xlwings. (I don't really use that package.) Under the covers, xlwings is relying on pywin32 on Windows and appscript on Mac, so you could use those lower-level packages directly.

For example, if you are on Windows, you could do this:

from win32com.client import Dispatch

xl = Dispatch('Excel.Application')

wb = xl.Workbooks.Add(my_xlsx_excel_file)

wb.SaveAs(my_xlsx_excel_file[:-1], FileFormat=56)

xl.Quit()

The 56 is a magic constant indicating Excel 97-2003 format (for Windows).

Naturally, there should be a corresponding way to do this on a Mac with appscript. Just be aware that the file format constants may be different than on Windows.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值