1.使用第三方库
python中处理excel表格,常用的库有xlrd(读excel)表、xlwt(写excel)表、openpyxl(可读写excel表)等。 xlrd读数据较大的excel表时效率高于openpyxl,所以我在写脚本时就采用了xlrd和xlwt这两个库。介绍及下载地址为:http://www.python-excel.org/ 这些库文件都没有提供修改现有excel表格内容的功能。一般只能将原excel中的内容读出、做完处理后,再写入一个新的excel文件。
1.安装
pip install xlwt
pip install xlrd
2.使用
1.导入模块
import xlrd #导入模块
2.获取一个工作表的数据
table = data.sheets()[0] #通过索引顺序获取,这个是个地址列表 #[u‘\u65e5\u671f‘, u‘\u5c0f\u65f6‘, u‘\u697c\u5c42‘, u‘\u5e97\u94fa\u53f7‘, u‘\u5e97\u94fa\u540d\u79f0‘, u‘\u4eba\u6570‘] table = data.sheet_by_index(0) #通过索引顺序获取 table = data.sheet_by_name(u‘Sheet1‘)#通过名称获取 #获取整行和整列的值(数组) table.row_values(i) table.col_values(i) #获取行数和列数 nrows = table.nrows ncols = table.ncols #循环行列表数据 for i in range(nrows ): print table.row_values(i) #单元格 cell_A1 = table.cell(0,0).value cell_C4 = table.cell(2,3).value #使用行列索引 cell_A1 = table.row(0)[0].value cell_A2 = table.col(1)[0].value
3.写入数据到一个sheel中
w = xlwt.Workbook()#创建一个写入的exel对象 sheet = w.add_sheet(‘sheet1‘)#添加一个sheet页 for i in range(len(buf)): print buf[i] sheet.write(i,0,buf[i].decode(‘utf8‘))#写入数据 w.save(outEfile) #将数据写入到保存文件,没有这一步数据在内存中
4.设置格式
创建一个样式对象,对其进行设置,之后应用到exel格式中。样式对象有很多设置,举例常用的几个,一个是字体front设置,一个是边框borders设置,一个是Pattern
style = xlwt.XFStyle() # 初始化样式
创建一个front设置,设置其字体等:
font = xlwt.Font() # 为样式创建字体 font.name = name # ‘Times New Roman‘#设置字体 font.bold = bold#设置字体颜色 font.color_index = 4 font.height = height#高度
创建一个borders设置:
borders = xlwt.Borders()#创建一个边框对象 borders.left = 1 borders.right = 1 borders.top = 1 borders.bottom = 1 borders.bottom_colour=0x3A
创建一个Pattern设置:
pattern = xlwt.Pattern() # Create the Pattern pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12 pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green,
应用到样式中:
style.borders = borders style.font = font style.pattern = pattern # Add Pattern to Style
最后演示结果图:
最后是官方实例,比较详细,有用到的可以看一下:
Examples Generating Excel Documents Using Python’s xlwt Here are some simple examples using Python’s xlwt library to dynamically generate Excel documents. Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:http://packages.python.org/ezodf/index.html The Simplest Example import xlwt workbook = xlwt.Workbook(encoding = ‘ascii‘) worksheet = workbook.add_sheet(‘My Worksheet‘) worksheet.write(0, 0, label = ‘Row 0, Column 0 Value‘) workbook.save(‘Excel_Workbook.xls‘) Formatting the Contents of a Cell import xlwt workbook = xlwt.Workbook(encoding = ‘ascii‘) worksheet = workbook.add_sheet(‘My Worksheet‘) font = xlwt.Font() # Create the Font font.name = ‘Times New Roman‘ font.bold = True font.underline = True font.italic = True style = xlwt.XFStyle() # Create the Style style.font = font # Apply the Font to the Style worksheet.write(0, 0, label = ‘Unformatted value‘) worksheet.write(1, 0, label = ‘Formatted value‘, style) # Apply the Style to the Cell workbook.save(‘Excel_Workbook.xls‘) Attributes of the Font Object font.bold = True # May be: True, False font.italic = True # May be: True, False font.struck_out = True # May be: True, False font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I font.colour_index = ? font.get_biff_record = ? font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height. font.name = ? font.outline = ? font.shadow = ? Setting the Width of a Cell import xltw workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) worksheet.write(0, 0, ‘My Cell Contents‘) worksheet.col(0).width = 3333 # 3333 = 1" (one inch). workbook.save(‘Excel_Workbook.xls‘) Entering a Date into a Cell import xlwt import datetime workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) style = xlwt.XFStyle() style.num_format_str = ‘M/D/YY‘ # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0 worksheet.write(0, 0, datetime.datetime.now(), style) workbook.save(‘Excel_Workbook.xls‘) Adding a Formula to a Cell import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) worksheet.write(0, 0, 5) # Outputs 5 worksheet.write(0, 1, 2) # Outputs 2 worksheet.write(1, 0, xlwt.Formula(‘A1*B1‘)) # Should output "10" (A1[5] * A2[2]) worksheet.write(1, 1, xlwt.Formula(‘SUM(A1,B1)‘)) # Should output "7" (A1[5] + A2[2]) workbook.save(‘Excel_Workbook.xls‘) Adding a Hyperlink to a Cell import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) worksheet.write(0, 0, xlwt.Formula(‘HYPERLINK("http://www.google.com";"Google")‘)) # Outputs the text "Google" linking to http://www.google.com workbook.save(‘Excel_Workbook.xls‘) Merging Columns and Rows import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) worksheet.write_merge(0, 0, 0, 3, ‘First Merge‘) # Merges row 0‘s columns 0 through 3. font = xlwt.Font() # Create Font font.bold = True # Set font to Bold style = xlwt.XFStyle() # Create Style style.font = font # Add Bold Font to Style worksheet.write_merge(1, 2, 0, 3, ‘Second Merge‘, style) # Merges row 1 through 2‘s columns 0 through 3. workbook.save(‘Excel_Workbook.xls‘) Setting the Alignment for the Contents of a Cell import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) alignment = xlwt.Alignment() # Create Alignment alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED style = xlwt.XFStyle() # Create Style style.alignment = alignment # Add Alignment to Style worksheet.write(0, 0, ‘Cell Contents‘, style) workbook.save(‘Excel_Workbook.xls‘) Adding Borders to a Cell # Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines. import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) borders = xlwt.Borders() # Create Borders borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D. borders.right = xlwt.Borders.DASHED borders.top = xlwt.Borders.DASHED borders.bottom = xlwt.Borders.DASHED borders.left_colour = 0x40 borders.right_colour = 0x40 borders.top_colour = 0x40 borders.bottom_colour = 0x40 style = xlwt.XFStyle() # Create Style style.borders = borders # Add Borders to Style worksheet.write(0, 0, ‘Cell Contents‘, style) workbook.save(‘Excel_Workbook.xls‘) Setting the Background Color of a Cell import xlwt workbook = xlwt.Workbook() worksheet = workbook.add_sheet(‘My Sheet‘) pattern = xlwt.Pattern() # Create the Pattern pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12 pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on... style = xlwt.XFStyle() # Create the Pattern style.pattern = pattern # Add Pattern to Style worksheet.write(0, 0, ‘Cell Contents‘, style) workbook.save(‘Excel_Workbook.xls‘) TODO: Things Left to Document - Panes -- separate views which are always in view - Border Colors (documented above, but not taking effect as it should) - Border Widths (document above, but not working as expected) - Protection - Row Styles - Zoom / Manification - WS Props? Source Code for reference available at: https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/
官方实例
最后是一个小实例,遇到了一个比较坑的东西,我想投机取巧,事前先把样式手动设置好,直接往里面写数据。这时我用到了copy,但是往里面写数据没问题,但是在保存的时候,老是报字符集的问题,这也是python2的一大问题吧。一天我也没解决掉,最后只能先放弃了。
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = ‘wyf‘ import ConfigParser import xlwt import xlrd import sys from xlutils.copy import copy import sys import codecs reload(sys) sys.setdefaultencoding(‘utf-8‘) a=[[‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘31‘, ‘snidel‘, 81], [‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘69‘, ‘Bout hent ique‘, 12], [‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘95‘, ‘ZARA‘, 254]] def set_style(name,height,bold=False): style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体 font.name = name # ‘Times New Roman‘ font.bold = bold font.color_index = 4 font.height = height pattern = xlwt.Pattern() # Create the Pattern pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12 pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = borders = xlwt.Borders() borders.left = 1 borders.right = 1 borders.top = 1 borders.bottom = 1 borders.bottom_colour=0x3A style.borders = borders style.font = font style.pattern = pattern # Add Pattern to Style return style def writeXlwt(result,row0,book,sheelName): worksheet = book.add_sheet(sheelName)#添加一个sheet页 print ‘*****=‘,row0 for i in range(len(result)+1): if i ==0: for f in range(0,len(row0)): worksheet.write(0,f,row0[f],set_style(‘Arial‘,220,True)) else: for a in range(len(result[i-1])): worksheet.row(i).write(a,result[i-1][a]) if __name__ ==‘__main__‘: #book = xlwt.Workbook(encoding = ‘utf-8‘) oldWb = xlrd.open_workbook(‘test123.xls‘,formatting_info=True) book = copy(oldWb) setattr(book,‘encoding‘,‘utf-8‘) #book = xlwt.Workbook() cf = ConfigParser.ConfigParser()#生成一个实例 #with codecs.open(‘config_dayueche.conf‘, encoding="utf-8" ) as f: cf.read("config_dayueche.conf") #读取配置文件 sheelList = cf.sections() for sheel in sheelList: row0 = cf.get(sheel,‘row0‘).split(‘;‘) writeXlwt(a,row0,book,sheel) book.save(‘test1232.xls‘)#打开一个工作薄
实例代码
时间: 2024-10-10 07:31:46