首先,简单介绍一下EXECL中工作簿和工作表的区别: 工作簿的英文是BOOK(WORKBOOK),工作表的英文是SHEET(WORKSHEET)。
1:使用python实现对Excel文件的读写,首先需要安装专用的模块(可以自己编写)xlrd,xlwt模块 2:读取excel数据(注意事项:sheet编号,行号,列号都是从索引0开始)
按 Ctrl+C 复制代码 按 Ctrl+C 复制代码
3:创建excel并写入数据
按 Ctrl+C 复制代码 按 Ctrl+C 复制代码
再看一个例子: 转载:Ryan in C++ 基本的write函数接口很简单:
1 """ 2 设置单元格样式 3 """ 4 import xlwt 5 6 7 def set_style(font_name, font_height, bold=False): 8 style = xlwt.XFStyle() # 初始化样式 9 10 font = xlwt.Font() # 为样式创建字体 11 font.name = font_name # 'Times New Roman' 12 font.bold = bold 13 font.color_index = 4 14 font.height = font_height 15 16 borders = xlwt.Borders() 17 borders.left = 6 18 borders.right = 6 19 borders.top = 6 20 borders.bottom = 6 21 22 style.font = font 23 style.borders = borders 24 25 return style 26 27 28 # 写excel 29 def write_excel(output_path): 30 f = xlwt.Workbook() # 创建工作簿 31 ''' 32 创建第一个sheet: 33 sheet1 34 ''' 35 sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) # 创建sheet 36 row0 = [u'业务',u'状态',u'北京',u'上海',u'广州',u'深圳',u'状态小计',u'合计'] 37 column0 = [u'机票',u'船票',u'火车票',u'汽车票',u'其它'] 38 status = [u'预订',u'出票',u'退票',u'业务小计'] 39 # 生成第一行 40 for i in range(0, len(row0)): 41 sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True)) 42 43 # 生成第一列和最后一列(合并4行) 44 i, j = 1, 0 45 while i < 4*len(column0) and j < len(column0): 46 sheet1.write_merge(i, i+3, 0, 0, column0[j], set_style('Arial', 220, True)) # 第一列 47 sheet1.write_merge(i, i+3, 7, 7) # 最后一列"合计" 48 i += 4 49 j += 1 50 51 sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True)) 52 53 # 生成第二列 54 i = 0 55 while i < 4*len(column0): 56 for j in range(0,len(status)): 57 sheet1.write(j+i+1, 1, status[j]) 58 i += 4 59 60 f.save(output_path) 61 62 63 if __name__ == '__main__': 64 write_excel('E:/demo.xls') # 保存文件.这里如果是.xlsx的话会打不开。
注意:如果对一个单元格重复操作,会引发error。所以在打开时加cell_overwrite_ok=True解决 table = file.add_sheet('sheet name',cell_overwrite_ok=True)
生成的demo.xls效果如下: |
|