![2e645f93cb204c330099d0022c257514.png](https://i-blog.csdnimg.cn/blog_migrate/c4f113d53b25262bccedb0d4c399291d.jpeg)
使用xlwt模块,可以对电子表格执行多个操作。例如,可以用Python编写或修改数据。此外,用户可能需要浏览各种工作表并根据某些条件检索数据,或者修改某些行和列并执行大量工作。
让我们看看如何使用Python创建和写入Excel工作表。
代码1:
# 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')
输出:
![eddb66c6d4c430fa11b91a8b86d82afe.png](https://i-blog.csdnimg.cn/blog_migrate/529b94e97c52f51d6894c808c1b23abf.jpeg)
代码2:在Excel中添加样式表
# 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")
输出:
![c760baacfced15ed32ae21940166dc72.png](https://i-blog.csdnimg.cn/blog_migrate/6d4ab2ff09c94d40c5a0f8e9774cbeea.jpeg)
代码3:向单元格添加多种样式
# 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")
输出:
![bad4f51e67bc6b643f6b269449370f98.png](https://i-blog.csdnimg.cn/blog_migrate/d7f618f54ded8fa6085e5f389989c030.jpeg)