使用Python寫入Excel工作表

使用Python寫入Excel工作表

使用xlwt模塊,可以對電子表格執行多個操作。例如,可以用Python編寫或修改數據。此外,用戶可能需要瀏覽各種工作表並根據某些條件檢索數據,或者修改某些行和列並執行大量工作。

讓我們看看如何使用Python創建和寫入Excel工作表。

代碼1

<code># Writing to an excel  
# sheet using Python 
import xlwt 
from xlwt import Workbook 
  
# Workbook is created 
wb = Workbook() 
  
# add_sheet is used to create sheet. 
sheet1 = wb.add_sheet('Sheet 1') 
  
sheet1.write(1, 0, 'ISBT DEHRADUN') 
sheet1.write(2, 0, 'SHASTRADHARA') 
sheet1.write(3, 0, 'CLEMEN TOWN') 
sheet1.write(4, 0, 'RAJPUR ROAD') 
sheet1.write(5, 0, 'CLOCK TOWER') 
sheet1.write(0, 1, 'ISBT DEHRADUN') 
sheet1.write(0, 2, 'SHASTRADHARA') 
sheet1.write(0, 3, 'CLEMEN TOWN') 
sheet1.write(0, 4, 'RAJPUR ROAD') 
sheet1.write(0, 5, 'CLOCK TOWER') 
  
wb.save('xlwt example.xls') /<code>

輸出:

使用Python寫入Excel工作表

代碼2:在Excel中添加樣式表

<code># importing xlwt module 
import xlwt 
  
workbook = xlwt.Workbook()  
  
sheet = workbook.add_sheet("Sheet Name") 
  
# Specifying style 
style = xlwt.easyxf('font: bold 1') 
  
# Specifying column 
sheet.write(0, 0, 'SAMPLE', style) 
workbook.save("sample.xls") /<code>

輸出:

使用Python寫入Excel工作表

代碼3:向單元格添加多種樣式

<code># importing xlwt module 
import xlwt 
  
workbook = xlwt.Workbook()  
  
sheet = workbook.add_sheet("Sheet Name") 
  
# Applying multiple styles 
style = xlwt.easyxf('font: bold 1, color red;') 
  
# Writing on specified sheet 
sheet.write(0, 0, 'SAMPLE', style) 
  
workbook.save("sample.xls") /<code>

輸出:

使用Python寫入Excel工作表


分享到:


相關文章: