使用 Python 格式化 Excel 中的单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1029500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting cells in Excel with Python
提问by Sasha
How do I format cells in Excel with python?
如何使用 python 格式化 Excel 中的单元格?
In particular I need to change the font of several subsequent rows to be regular instead of bold.
特别是我需要将几个后续行的字体更改为常规而不是粗体。
回答by mechanical_meat
Using xlwt:
使用xlwt:
from xlwt import *
font0 = Font()
font0.bold = False
style0 = XFStyle()
style0.font = font0
wb = Workbook()
ws0 = wb.add_sheet('0')
ws0.write(0, 0, 'myNormalText', style0)
font1 = Font()
font1.bold = True
style1 = XFStyle()
style1.font = font1
ws0.write(0, 1, 'myBoldText', style1)
wb.save('format.xls')
回答by Brendan Wood
For using Python for Excel operations in general, I highly recommend checking out this site. There are three python modules that allow you to do pretty much anything you need: xlrd(reading), xlwt(writing), and xlutils(copy/modify/filter). On the site I mentioned, there is quite a bit of associated information including documentation and examples. In particular, you may be interested in this example. Good luck!
对于一般使用 Python 进行 Excel 操作,我强烈建议您查看此站点。有三个 python 模块可以让你做任何你需要的事情:xlrd(阅读)、xlwt(写作)和xlutils(复制/修改/过滤)。在我提到的站点上,有相当多的相关信息,包括文档和示例。特别是,您可能对这个例子感兴趣。祝你好运!
回答by spiffyman
Hereis a brief introduction to using xlwt
and the complementary xlrd
(for reading .xls
files). However, the Reddit threadwhere I discovered that article has a huge number of useful bits of advice, including some cautionary notes and how to use the win32com
module to write Excel files better (see this comment, for example) - frankly, I think the code is easier to read/maintain. You can probably learn a lot more over at the pretty active python-excelgroup.
这里简单介绍一下使用xlwt
和补充xlrd
(用于阅读.xls
文件)。然而,我发现这篇文章的 Reddit线程有大量有用的建议,包括一些警告说明以及如何使用win32com
模块更好地编写 Excel 文件(例如,请参阅此评论) - 坦率地说,我认为代码更容易阅读/维护。您可能可以在非常活跃的python-excel小组中学到更多。
回答by Alex Martelli
For generic examples of Excel scripting from Python, this snippetis very handy. It doesn't specifically do the "change font to regular", but that's just range.Font.Bold = False
in a function otherwise very similar to the set_border
one in that snippet.
对于从 Python 编写 Excel 脚本的通用示例,此代码段非常方便。它没有专门执行“将字体更改为常规字体”,但这只是range.Font.Bold = False
在一个函数中,否则与set_border
该代码段中的函数非常相似。