2022年 11月 5日

python如何导出数据到excel文件

python导出数据到excel文件的方法:

1、调用Workbook()对象中的add_sheet()方法

 
wb = xlwt.Workbook()

ws = wb.add_sheet('A Test Sheet')
  • 1
  • 2
  • 3
  • 4

2、通过add_sheet()方法中的write()函数将数据写入到excel中,然后使用save()函数保存excel文件

 
ws.write(0, 0, 1234.56, style0)

ws.write(1, 0, datetime.now(), style1)

ws.write(2, 0, 1)

ws.write(2, 1, 1)

ws.write(2, 2, xlwt.Formula("A3+B3"))

  

wb.save('example.xls')

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

完整代码如下:

 
import xlwtfrom datetime import datetime

  

style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',num_format_str='#,##0.00')

style1 = xlwt.easyxf(num_format_str='D-MMM-YY')

  

wb = xlwt.Workbook()

ws = wb.add_sheet('A Test Sheet')

  

ws.write(0, 0, 1234.56, style0)

ws.write(1, 0, datetime.now(), style1)

ws.write(2, 0, 1)

ws.write(2, 1, 1)

ws.write(2, 2, xlwt.Formula("A3+B3"))

  

wb.save('example.xls')

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

程序执行结果如下:

091438322905708.png