Python处理Excel文档之openpyxl,,openpyxl 可
Python处理Excel文档之openpyxl,,openpyxl 可
openpyxl 可以很好的处理 2010版本以上的表格。
示例:
1 #coding:utf8 2 ‘‘‘ 3 Created on 2018年8月18日 4 5 @author: Administrator 6 ‘‘‘ 7 from openpyxl import Workbook 8 import datetime 9 wb = Workbook()10 11 # grab the active worksheet12 ws = wb.active13 14 # Data can be assigned directly to cells15 ws[‘A1‘] = "班级人员统计表"16 17 # Rows can also be appended18 list_str=["记录时间","学号","姓名","性别","年龄"]19 ws.append(list_str)20 21 list_str2=["1","诸葛亮","男","89"]22 time1=datetime.date.today()23 list_str2.insert(0, time1)24 ws.append(list_str2)25 26 # 如果你要在已经有的数据上进行修改,会自动覆盖掉,原有的数据27 # import datetime28 # ws[‘A2‘] = datetime.datetime.now()29 30 # Save the file31 wb.save("sample.xlsx")
在内存中处理一个工作簿:
创建一个工作簿
没有必要利用openpyxl先去创建一个文件系统上的文件然后才能开始使用。你只要导入工作簿类,然后开始使用它吧。
>>> from openpyxl import Workbook>>> wb = Workbook()
A workbook is always created with at least one worksheet. You can get it by using theopenpyxl.workbook.Workbook.active()property
一个工作簿被创建后,总会在里面默认创建一张工作表。你可以通过使用方法openpyxl.workbook.Workbook.active()来得到它。
ws = wb.active
默认状态下,函数the _active_sheet_index property的 index设置为0,除非你手动修改它的数值,否则的话,你用这个方法,只会拿到第一个工作表。
1 @property 2 def active(self): 3 """Get the currently active sheet or None 4 5 :type: :class:`openpyxl.worksheet.worksheet.Worksheet` 6 """ 7 try: 8 return self._sheets[self._active_sheet_index] 9 except IndexError:10 pass11 12 @active.setter13 def active(self, value):14 """Set the active sheet"""15 self._active_sheet_index = value16 17 def create_sheet(self, title=None, index=None):18 """Create a worksheet (at an optional index).19 20 :param title: optional title of the sheet21 :type title: unicode22 :param index: optional position at which the sheet will be inserted23 :type index: int24 25 """26 if self.read_only:27 raise ReadOnlyWorkbookException(‘Cannot create new sheet in a read-only workbook‘)28 29 if self.write_only :30 new_ws = WriteOnlyWorksheet(parent=self, title=title)31 else:32 new_ws = Worksheet(parent=self, title=title)33 34 self._add_sheet(sheet=new_ws, index=index)35 return new_wsView Code
可以通过openpyxl.workbook.Workbook.create_sheet()方法,创建工作表。
wb.create_sheet("mysheet", 1)wss=wb.create_sheet()ws1 = wb.create_sheet("Mysheet111") # insert at the end (default)ws2 = wb.create_sheet("Mysheet222", 0) # insert at first position
工作表的名字是自动命令。按照列表(Sheet, Sheet1, Sheet2, …)的内容,顺序命名。你也可以自定义工作表名字。
ws.title = "New Title"
默认情况下,包含此标题的选项卡的背景颜色为白色。您可以将此更改为为sheet_properties提供RRGGBB颜色代码。tabColor属性:
ws.sheet_properties.tabColor = "1072BA"
Python处理Excel文档之openpyxl
相关内容
- 安装python的第三方库 geopandas,, 直接下载,geop
- python数据类型(一),,python3中主要
- python之子类继承父类时进行初始化的一些问题,,直接看
- python 创建游标,,import pym
- python并发编程-gevent使用大全,,一、gevent实现
- 万张PubFig人脸数据实现基于python+OpenCV的人脸特征定位程
- Python鐨勮捣婧愪笌璇炵敓,,鏍囩锛?a hre
- 【Python】Python库之虚拟现实,,【Python】Py
- python鍐欎竴涓猚mdb绠$悊绯荤粺,,鏍囩锛?a hre
- Python之禅中的几句话--传说中的蛇宗总纲,,Simple is
评论关闭