从Python轻松编写格式化的Excel:从格式化的Excel开始,在Python中使用它,然后从Python重新生成Excel [英] Easily write formatted Excel from Python: Start with Excel formatted, use it in Python, and regenerate Excel from Python

查看:323
本文介绍了从Python轻松编写格式化的Excel:从格式化的Excel开始,在Python中使用它,然后从Python重新生成Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从Python创建具有良好格式的Excel电子表格.我想通过以下方式做到这一点:

I have to create Excel spreadsheet with nice format from Python. I thought of doing it by:

  1. 我从Excel开始,因为它很容易格式化:我在Excel中编写 我想要的模型,格式好
  2. 我是从Python读到的
  3. 我从Python创建具有相同格式的Excel电子表格
  1. I start in Excel as it is very easy to format: I write in Excel the model I want, with the good format
  2. I read this from Python
  3. I create from Python an Excel spreadsheet with the same format

最后,目的是从Python Excel电子表格创建文件,但是使用xlwt进行格式化需要花费大量时间,因此我想到先在Excel中进行格式化来提供帮助.

In the end, the purpose is to create from Python Excel spreadsheets, but formatting with xlwt takes a lot of time, so I thought of formatting first in Excel to help.

我已经研究了实现此目的的简便方法,但没有找到任何方法.我可以坚持使用当前的工作解决方案,在Python中使用xlwt创建格式化的Excel,但是使用起来很尴尬.

I have researched for easy ways to doing this but haven't found any. I can stick to my current working solution, using xlwt in Python to create formatted Excel, but it is quite awkward to use.

感谢您的回复

推荐答案

感谢您的答复.我在使用python的样式保存样式中找到了要查找的内容xlrd,xlwt和xlutils.copy .代码如下.

Thanks for your replies. I've found what I was searching for at Preserving styles using python's xlrd,xlwt, and xlutils.copy. The code is below.

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') 

这篇关于从Python轻松编写格式化的Excel:从格式化的Excel开始,在Python中使用它,然后从Python重新生成Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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