2017-05-16 280 views
2

首次創建工作簿時如何使用xlswriter永久設置字體大小?XlsxWriter設置全局字體大小

我想:

book = xlsxwriter.Workbook(os.getcwd() + '\\test.xlsx') 
sheet1 = book.add_worksheet() 
format = book.add_format() 
format.set_font_size(10) 

但我仍然得到默認的大小11的輸出。什麼是問題?

回答

2

1,對於單個細胞的字體大小,您必須將format傳遞給write這樣的:

workbook = xlsxwriter.Workbook('demo.xlsx') 
worksheet = workbook.add_worksheet() 

# Add a bold format to use to highlight cells. 
bold = workbook.add_format({'bold': True}) 
# Add a font size 10 format. 
format = workbook.add_format() 
format.set_font_size(10) 
# Write some simple text. 
worksheet.write('A1', 'Hello', format) 

# Text with formatting. 
worksheet.write('A2', 'World', bold) 

# Write some numbers, with row/column notation. 
worksheet.write(2, 0, 123) 
worksheet.write(3, 0, 123.456) 


workbook.close() 

Hello將被設置爲字體大小10

enter image description here

更新: 2,對於所有的細胞字體大小,您可以設置工作簿的默認格式:

import xlsxwriter 
workbook = xlsxwriter.Workbook('demo.xlsx') 

# default cell format to size 10 
workbook.formats[0].set_font_size(10) 

worksheet = workbook.add_worksheet() 


# Write some simple text. 
worksheet.write('A1', 'Hello') 

worksheet.write('A2', 'World') 

# Write some numbers, with row/column notation. 
worksheet.write(2, 0, 123) 
worksheet.write(3, 0, 123.456) 

workbook.close() 

所有細胞會變成字體大小10:

enter image description here

+0

有沒有什麼方法可以在全局範圍內設置?我寫了很多次這個工作表/書,我想避免每次都通過它,因爲我希望它都大小10 – guy

+0

是的,請檢查更新的答案 –

+2

解決方法是好的,但請注意,它打破了圖像,圖形和插入到工作表中的其他對象。這是XlsxWriter當前不支持此功能的主要原因。 – jmcnamara