我正在使用xlrd
编辑Excel工作表中的几个单元格(.xls)。我能够保留已编辑信息的单元格格式(using this little hack)。但是,保存文件时,文档中的所有图像都将丢失。有没有办法保留它们?
我知道xlsxwrite
可以将图片插入到工作表中,但不幸的是,该文件不是.xlsx。
以下是代码:
from xlrd import open_workbook
from xlutils.copy import copy
class Writetoxls(object):
def __init__(self, ip, mac, ssid, wifipass, user, password):
self.ip = ip
self.mac = mac
self.ssid = ssid
self.wifipass = wifipass
self.user = user
self.password = password
inBook = open_workbook('data.xls', formatting_info=True)
outBook = copy(inBook)
def _getOutCell(outSheet, colIndex, rowIndex):
""" HACK: Extract the internal xlwt cell representation. """
row = outSheet._Worksheet__rows.get(rowIndex)
if not row: return None
cell = row._Row__cells.get(colIndex)
return cell
def setOutCell(outSheet, col, row, value):
""" Change cell value without changing formatting. """
# HACK to retain cell style.
previousCell = _getOutCell(outSheet, col, row)
# END HACK, PART I
outSheet.write(row, col, value)
# HACK, PART II
if previousCell:
newCell = _getOutCell(outSheet, col, row)
if newCell:
newCell.xf_idx = previousCell.xf_idx
# END HACK
outSheet = outBook.get_sheet(0)
setOutCell(outSheet, 3, 7, mac)
setOutCell(outSheet, 4, 16, ssid)
setOutCell(outSheet, 4, 17, wifipass)
outBook.save('output.xls')
谢谢。