我必须从 Python 创建格式良好的 Excel 电子表格。我想通过以下方式做到这一点:
- 我从 Excel 开始,因为它很容易格式化:我在 Excel 中编写
我想要的型号,格式良好
- 我从 Python 中读到了这个
- 我从 Python 创建一个具有相同格式的 Excel 电子表格
最后的目的是从Python创建Excel电子表格,但是用xlwt格式化需要很多时间,所以我想到先在Excel中格式化来帮忙。
我已经研究了执行此操作的简单方法,但还没有找到。我可以坚持我当前的工作解决方案,在Python中使用xlwt创建格式化的Excel,但使用起来相当尴尬。
感谢您的任何回复
感谢您的回复。我找到了我要寻找的东西使用 python 的 xlrd、xlwt 和 xlutils.copy 保留样式 https://stackoverflow.com/questions/3723793/preserving-styles-using-pythons-xlrd-xlwt-and-xlutils-copy。代码如下。
import xlrd
import xlutils.copy
inBook = xlrd.open_workbook('input.xls', formatting_info=True)
outBook = xlutils.copy.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, 5, 5, 'Test')
outBook.save('output.xls')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)