Python 如何在excel中加粗csv数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3749020/
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
how to bold csv data in excel?
提问by Jakir Hosen Khan
I work on a python(django) project. I write csv code as follows,
我在一个 python(django) 项目上工作。我写的csv代码如下,
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=DueDateWiseSearch.csv'
writer = csv.writer(response)
writer.writerow(['Infant Name','Mother Name','Mother Address',
'Next Vaccine Dose','Due date','Coments'])
this row is the header and I need to bold all header text. I download csv as ms "Excel" file.
这一行是标题,我需要将所有标题文本加粗。我将 csv 下载为 ms“Excel”文件。
How can I do it? Please help!
我该怎么做?请帮忙!
回答by SingleNegationElimination
There's no way to do that in CSV. You could all caps the output, or you could use another format that supports text styles.
在 CSV 中没有办法做到这一点。您可以将输出全部大写,也可以使用其他支持文本样式的格式。
回答by mkoistinen
There is no way to do that with CSV that I know of, but you might consider using the old SYLK formator Office XML format.
我所知道的 CSV 无法做到这一点,但您可以考虑使用旧的SYLK 格式或Office XML 格式。
回答by Tauren
回答by chmullig
A more modern alternative is xlsxcessivefor exporting an Excel 2007+ .xlsx file. Here's an example that makes the header row slightly larger and bold. It's really not too hard, and documented pretty well.
更现代的替代方法是xlsxcessive,用于导出 Excel 2007+ .xlsx 文件。这是一个使标题行稍大且粗体的示例。这真的不太难,而且记录得很好。
from xlsxcessive.xlsx import Workbook, save
#Create some fake test data
import urllib, random
words = [x.strip().title() for x in urllib.urlopen('http://dictionary-thesaurus.com/wordlists/Nouns%285,449%29.txt').readlines()]
names = []
for i in range(25):
address = '%s %s %s' % (random.randint(0, 100000), random.choice(words), random.choice(['Ave', 'St', 'Blvd', 'Ct', 'Ln']))
names.append((random.choice(words), random.choice(words), address))
#Create the workbook and sheet
wb = Workbook()
s1 = wb.new_sheet('Sheet 1')
#Create the bold style for the header row
headerfmt = wb.stylesheet.new_format()
headerfmt.font(size=14, bold=True)
#Write out the header row
header = ['Infant Name','Mother Name','Mother Address',]
for col, label in enumerate(header):
s1.cell(coords=(0,col), value=label, format=headerfmt)
#Write out the data
for rownumber, rowvalues in enumerate(names, start=1):
for col, value in enumerate(rowvalues):
s1.cell(coords=(rownumber, col), value=value)
save(wb, 'stackoverflow_problem.xlsx')

