python 写入 excel

今天要把统计数据写入Excel表格,需要用到python的xlwt模块,找了个例子:
import xlwt
file = xlwt.Workbook()                # 注意这里的Workbook首字母是大写
table = file.add_sheet('sheet name')  # 新建一个sheet

table.write(0,0,'test')               # 写入数据table.write(行,列,value)

# 如果对一个单元格重复操作,会引发
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
# 所以在打开时加cell_overwrite_ok=True解决

table = file.add_sheet('sheet name',cell_overwrite_ok=True)
file.save('demo.xls')     # 保存文件

# 另外,使用style
style = xlwt.XFStyle()    # 初始化样式
font = xlwt.Font()        # 为样式创建字体
font.name = 'Times New Roman'
font.bold = True
style.font = font         #为样式设置字体
table.write(0, 0, 'some bold Times text', style) # 使用样式
一次写一格,格式还不好看,坑爹啊。
经过千辛万苦,终于找到了个包装好的方法,不知道那个大神写的,膜拜下python 写入 excel - guotengfei19880205 - guotengfei19880205的博客
def write_xls(file_name, sheet_name, headings, data, heading_xf, data_xfs):     
    book = xlwt.Workbook(encoding='utf-8') 
    sheet = book.add_sheet(sheet_name)     
    rowx = 0      
    for colx, value in enumerate(headings):         
        sheet.write(rowx, colx, value,heading_xf)      
    sheet.set_panes_frozen(True) # frozenheadings instead of split panes      
    sheet.set_horz_split_pos(rowx+1) # ingeneral, freeze after last heading row     
    sheet.set_remove_splits(True) # if userdoes unfreeze, don't leave a split there     
    for row in data:         
        rowx += 1          
        for colx, value in enumerate(row):              
            sheet.write(rowx, colx, value,data_xfs[colx])     
    book.save(file_name)

def main():
    
    import sys      
    mkd = datetime.date      
    hdngs = ['Date', 'Stock Code', 'Quantity','Unit Price', 'Value', 'Message']      
    kinds = 'date    text          int         price         money    text'.split()     
    data = [[mkd(2007, 7, 1), 'ABC', 1000,1.234567, 1234.57, ''],  [mkd(2007, 12, 31), 'XYZ', -100,4.654321, -465.43, 'Goods returned'],] + [[mkd(2008, 6, 30), 'PQRCD', 100,2.345678, 234.57, ''],] * 100        
    heading_xf = ezxf('font: bold on; align:wrap on, vert centre, horiz center')     
    kind_to_xf_map = {'date':ezxf(num_format_str='yyyy-mm-dd'),         
                      'int': ezxf(num_format_str='#,##0'),          
                      'money': ezxf('font: italic on;pattern: pattern solid, fore-colour grey25', num_format_str='$#,##0.00'),          
                      'price': ezxf(num_format_str='#0.000000'),         
                      'text': ezxf(),}  
         
    data_xfs = [kind_to_xf_map[k] for k in kinds]   
        
    write_xls('xlwt_easyxf_simple_demo.xls','Demo', hdngs, data, heading_xf, data_xfs) 
 
很好用,谢谢大神啊。
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页