Openpyxl basic function demo code

demo code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
summary description
- openpyxl basic功能练习
- https://openpyxl.readthedocs.io/en/default/usage.html
:REQUIRES: :TODO: :AUTHOR: Pengtao.Fan
:ORGANIZATION:
:CONTACT: fanpengtao@gmail.com
:SINCE: Sun Aug 7 21:21:38 2016
:VERSION: 0.1
"""
#===============================================================================
# PROGRAM METADATA
#===============================================================================
__author__ = ''
__contact__ = ''
__copyright__ = ''
__license__ = ''
__date__ = 'Sun Aug 7 21:21:38 2016'
__version__ = '0.1' #===============================================================================
# IMPORT STATEMENTS
#=============================================================================== #from visual import * # IMPORTS NumPy.*, SciPy.*, and Visual objects (sphere, box, etc.)
#import matplotlib.pyplot as plt # plt.plot(x,y) plt.show()
#from pylab import * # IMPORTS NumPy.*, SciPy.*, and matplotlib.*
#import os # os.walk(basedir) FOR GETTING DIR STRUCTURE
#import pickle # pickle.load(fromfile) pickle.dump(data, tofile)
#from tkFileDialog import askopenfilename, askopenfile
#from collections import namedtuple
#from ctypes import *
#import glob
#import random
#import cv2
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import FORMULAE #to check the name of a formula
import pprint
import datetime
#===============================================================================
# METHODS
#===============================================================================
class OpenpyxlStudy(): def __init_(self):
pass
def getxl(self):
wb = load_workbook(filename = 'test.xlsx')
pprint.pprint(wb.get_sheet_names())
sheet_ranges = wb['ov']
#f14 = sheet_ranges['F14'] #<Cell ov.F14>
f14 = sheet_ranges['F14'].value #DEE
#f14 = sheet_ranges.cell('F14').value
#f14 = sheet_ranges.cell(raw = 15, column = 14)
print(f14)
def setxl(self):
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active #设置下次打开时的活动窗格
ws1.title = "range names"
for row in range(1, 40):
ws1.append(range(600))
ws2 = wb.create_sheet(title="Pi")
ws2['F5'] = 3.14
ws3 = wb.create_sheet(title="Data")
for row in range(10, 20):
for col in range(27, 54):
#这种cell赋值方法比较新
#注意get_column_letter
_ = ws3.cell(column=col, row=row, value="%s" % get_column_letter(col))
print(ws3['AA10'].value)
wb.save(filename = dest_filename)
def Fommats(self):
'''Using number formats'''
#dest_filename = 'empty_book.xlsx'
#wb = load_workbook(filename = dest_filename)
wb = Workbook(guess_types=True)
ws = wb.active
# set data using a Python datetime
ws['A1'] = datetime.datetime.now()
print(ws['A1'].number_format)
# set percentage using a string followed by the percent sign
ws['B1'] = '3.14%'
print(ws['B1'].value)
print(ws['B1'].number_format)
wb.save("fommats.xlsx")
def Formulae(self):
'''excel自带数学公式功能'''
wb = Workbook()
ws = wb.active
# 添加excel自带的sum公式
ws['A1'] = '=SUM(1, 2)'
wb.save('formula.xlsx') if "HEX2DEC" in FORMULAE:
print("HEX2DEC in FORMULAE")
else:
print("HEX2DEC not in FORMULAE")
def MergeCells(self):
'''合并单元格'''
'''Merge / Unmerge cells'''
wb = Workbook()
ws = wb.active #设置下次打开时的活动窗格
ws = wb.create_sheet(title="MergeCells")
ws.merge_cells('A1:B2')
#or
#ws.merge_cells(start_row=0,start_column=0,end_row=8,end_column=8)
ws['A1'] = 'You should see three logos below' # create an image
#img = Image('image.jpg')
# add to worksheet and anchor next to cells
#ws.add_image(img, 'A1')
wb.save('MergeCells.xlsx')
pass
def UnMergeCells(self):
'''拆分单元格'''
'''Merge / Unmerge cells'''
pass
def InsertImage(self):
'''inset image at A1 cell'''
wb = Workbook()
ws = wb.active #设置下次打开时的活动窗格
ws.title = 'InsertImageSheet'
ws.merge_cells('A1:D7')
ws['A1'] = 'You should see three logos below' # create an image
img = Image('image.jpg')
# add to worksheet and anchor next to cells
ws.add_image(img, 'A1') #==============================================================================
# '''虽然A1占用了A3 格子,但不能如下写。'''
# ws2 = wb.create_sheet('SecondImageSheet')
# ws2.merge_cells('A1:D7')
# ws2['A3'] = 'You should see three logos below'
#
# # create an image
# img = Image('image.jpg')
# # add to worksheet and anchor next to cells
# ws.add_image(img, 'A3')
#============================================================================== wb.save('InsertImage.xlsx') def Foldcolumns(self):
'''隐藏某些列'''
wb = Workbook(True)
ws = wb.create_sheet()
ws.column_dimensions.group('A','D', hidden=True)
wb.save('Foldcolumns.xlsx') #===============================================================================
# MAIN METHOD AND TESTING AREA
#===============================================================================
def main():
"""Description of main()"""
test = OpenpyxlStudy()
#test.getxl()
#test.setxl()
#test.Fommats()
#test.Formulae()
#test.MergeCells()
#test.InsertImage()
test.Foldcolumns() if __name__ == '__main__':
main()

penpyxl basic function demo code的更多相关文章

  1. RAD Studio Demo Code和几个国外FMX网站 good

    FireMonkey X –  Amazing overview of FireMonkey FMX Feeds – All your FireMonkey news in one place FMX ...

  2. ps2keyboard demo code for 8052

    #pragma code symbols debug objectextend #include <reg51.h> /* special function register declar ...

  3. c++ demo code

    /* //多继承 #include <iostream> using namespace std; class Sofa { public: Sofa(); ~Sofa(); void s ...

  4. ( ! ) Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in D:\demo\code\yolo\index\index.php on li

    sql语句为:$sql="select count(*) from com where a_id=$v['id']"; 出现以下错误: 原因: 变量没有用花括号引起来 改为:  $ ...

  5. npm install 安装报错:npm ERR! EPERM npm ERR! -4048 npm ERR! Error: EPERM: operation not permitted, unlink 'D:\test\demo\code\materialT\node_modules\.staging'

    更新项目依赖包,删除掉package-lock.json.node_modules,运行npm install,报如上错误信息,查询资料说是没有权限,本人用管理员身份打开powershell,运行np ...

  6. swagger demo code

    //Application 开启注解 @EnableSwagger2public class Application { public static void main(String[] args) ...

  7. 《JavaScript高级程序设计 第3版》-学习笔记-3

    P84-P137页, 这一章看的真久,这个月事太多了.有些内容在代码注释里没提出来了 1.JS强大的数组类型,元素类型任意,提供了非常多的操作数组的方法和属性 /* 数组类型 */ //stack v ...

  8. Delphi xe7 FireMonkey / Mobile (Android, iOS)生成 QR Code完整实例

    这个实例在windows.OS X.IOS和Android等平台运行正常.本文参考这个网站提供的方法:http://zarko-gajic.iz.hr/firemonkey-mobile-androi ...

  9. [Quote]Creating basic Excel workbook with Open XML

    Creating basic Excel workbook with Open XML [Quote from]http://www.codeproject.com/Articles/371203/C ...

随机推荐

  1. Rails Array method second/third/second_to_last

    http://api.rubyonrails.org/classes/Array.html#method-i-second [27] pry(main)> list = ["a&quo ...

  2. java中面向对象的一些知识(一)

    一:基本概念 举例:写一个程序,实现如下功能: 一群宠物,宠物有各种类型,如猫.狗.企鹅等 让这群宠物,按照各自的能力不同,进行各种比赛(如爬树.游泳.跳水):扩展性需求: 游泳比赛游泳池的参数.飞盘 ...

  3. AxureRp 打开SVN上的团队项目

    打开Axure,在菜单项中,点击 "团队" 菜单,选择 "获取团队项目": 切换到 "SVN" 选项, 填写正确的Axure项目的路径,打开 ...

  4. python supervisor使用

    Supervisor 是基于 Python 的进程管理工具,只能运行在 Unix-Like 的系统上,也就是无法运行在 Windows 上.Supervisor 官方版目前只能运行在 Python 2 ...

  5. 55. 2种方法求字符串的组合[string combination]

    [本文链接] http://www.cnblogs.com/hellogiser/p/string-combination.html [题目] 题目:输入一个字符串,输出该字符串中字符的所有组合.举个 ...

  6. iOS Swift的一些小知识(不断补充)

    1. 在swift文件里是不能写c语言函数的,不兼容c,直接报错.想调用c语言函数,就要利用系统提供的桥接功能,就如同swfit中调用oc一样! 2.swift 2.0后提供了@convention( ...

  7. JS Date.parse() 函数详解

    Date.parse()函数用于分析一个包含日期的字符串,并返回该日期与 1970 年 1 月 1 日午夜之间相差的毫秒数. 该函数属于Date对象,所有主流浏览器均支持该函数. 语法 Date.pa ...

  8. iOS delegate

    有两个scene,分别为Scene A和Scene B.Scene A上有一个UIButton(Button A)和一个UILable(Lable A):Scene B上有一个UITextFiled( ...

  9. shell 多行注释

    :<<! 要注释的内容 要注释的内容 要注释的内容 !

  10. Redis

    1. sds类型 sds为一种抽象数据结构 typedef char *sds;struct sdshdr { // buf 已占用长度int len; // buf 剩余可用长度int free;  ...