REF:http://www.cnblogs.com/MrLJC/p/3715783.html
https://www.programering.com/a/MTMyQDNwATU.html
https://openpyxl.readthedocs.io/en/stable/tutorial.html#saving-as-a-str
一、读excel表
读excel要用到xlrd模块,官网安装(http://pypi.python.org/pypi/xlrd)。然后就可以跟着里面的例子稍微试一下就知道怎么用了。大概的流程是这样的:
1、导入模块
import xlrd
2、打开Excel文件读取数据
data = xlrd.open_workbook('excel.xls')
3、获取一个工作表
1 table = data.sheets()[0] #通过索引顺序获取
2 table = data.sheet_by_index(0) #通过索引顺序获取
3 table = data.sheet_by_name(u'Sheet1')#通过名称获取
4、获取整行和整列的值(返回数组)
table.row_values(i)
table.col_values(i)
5、获取行数和列数
table.nrows
table.ncols
6、获取单元格
table.cell(0,0).value
table.cell(2,3).value
二、写excel表
写excel表要用到xlwt模块,官网下载(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:
1、导入模块
import xlwt
2、创建workbook(其实就是excel,后来保存一下就行)
workbook = xlwt.Workbook(encoding = 'ascii')
3、创建表
worksheet = workbook.add_sheet('My Worksheet')
4、往单元格内写入内容
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
5、保存
workbook.save('Excel_Workbook.xls')
"""
#-------------------------------xlwt 1---------------------------------------
import xlwt
def main():
""""""
book = xlwt.Workbook()
sheet1 = book.add_sheet("PySheet1")
cols = ["A", "B", "C", "D", "E"]
txt = "Row %s, Col %s"
for num in range(5):
row = sheet1.row(num)
for index, col in enumerate(cols):
value = txt % (num+1, col)
row.write(index, value)
book.save("test.xls")
sheet = book.add_sheet('Sheet 1')
if __name__ == "__main__":
main()
#----------------------------------------------------------------------
"""
#-----------------------------xlrd 1-----------------------------------------
from xlutils.copy import copy
import xlrd
import xlwt
rb = xlrd.open_workbook('test.xls')
def main():
#rb = xlrd.open_workbook('sample.xls')
rb = xlrd.open_workbook('test.xls')
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(5, 5, 'sample 2')
#sheet.write_merge(3, 4, 3, 4, 'sample 3', xlwt.easyxf('align: horse center, vert center'))
wb.save('test.xls')
sheet = wb.add_sheet('Sheet 1')
wb.save('test.xls')
if __name__ == '__main__':
main()
#----------------------------------------------------------------------
2
openpyxl for(xlsx format)REF: https://openpyxl.readthedocs.io/en/stable/tutorial.html#saving-as-a-stream
https://openpyxl.readthedocs.io/en/stable/usage.html#write-a-workbook
from openpyxl import Workbook
from openpyxl import load_workbook
import datetime
from openpyxl.utils import get_column_letter
#REF: https://openpyxl.readthedocs.io/en/stable/
#REF https://openpyxl.readthedocs.io/en/stable/usage.html#write-a-workbook
#REF https://openpyxl.readthedocs.io/en/stable/tutorial.html
#REF https://stackoverflow.com/questions/35693094/worksheet-range-names-does-not-exist-keyerror-in-openpyxl?rq=1
#----------------------------------Simple usage------------------------------
#Write a workbook
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):
_ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
print(ws3['AA10'].value)
wb.save(filename = dest_filename)
#Read an existing workbook
wb = load_workbook(filename = 'empty_book.xlsx')
sheet_ranges = wb['range names']
print(sheet_ranges['D18'].value)
#Note
#There are several flags that can be used in load_workbook.
#guess_types will enable or disable (default) type inference when reading cells.
#data_only controls whether cells with formulae have either the formula (default) or
#the value stored the last time Excel read the sheet.
#keep_vba controls whether any Visual Basic elements are preserved or not (default).
#If they are preserved they are still not editable.
#Warning
#openpyxl does currently not read all possible items in an Excel file so images and
#charts will be lost from existing files if they are opened and saved with the same name.
#----------------------------------Simple usage end------------------------------
wb = Workbook()
# grab the active worksheet
ws = wb.active
"""
# Data can be assigned directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("sample.xlsx")
"""
#------------------------creat write------------------------------
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):
_ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
print(ws3['AA10'].value)
wb.save(filename = dest_filename)
#-------------------------read------------------------
wb = load_workbook(filename = 'sample.xlsx')
# To display all of the available worksheet names
sheets = wb.sheetnames
print (sheets)
# To work with the first sheet (by name)
ws = wb[sheets[0]]
print (ws['A1'].value)
# To work with the active sheet
ws = wb.active
print (ws['A1'].value)
# To work with the active sheet (alternative method)
ws = wb.get_active_sheet()
print (ws['A1'].value)
#--------------------------------Tutorial-----------------------------------------------
#--------------------------------Create a workbook--------------------------------------
#There is no need to create a file on the filesystem to get started with openpyxl.
# Just import the Workbook class and start work:
wb = Workbook()
#A workbook is always created with at least one worksheet. You can get it by using
# the Workbook.active property:
ws = wb.active
"""
Note:
This is set to 0 by default. Unless you modify its value,
you will always get the first worksheet by using this method.
"""
#You can create new worksheets using the Workbook.create_sheet() method:
ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
# or
ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
#Sheets are given a name automatically when they are created. They are numbered
# in sequence (Sheet, Sheet1, Sheet2, …). You can change this name at any time
# with the Worksheet.title property:
ws.title = "New Title"
#The background color of the tab holding this title is white by default.
# You can change this providing an RRGGBB color code to the
# Worksheet.sheet_properties.tabColor attribute:
ws.sheet_properties.tabColor = "1072BA"
#Once you gave a worksheet a name, you can get it as a key of the workbook:
ws3 = wb["New Title"]
#You can review the names of all worksheets of the workbook with the
# Workbook.sheetname attribute
print(wb.sheetnames)
#You can loop through worksheets
for sheet in wb:
print(sheet.title)
#You can create copies of worksheets within a single workbook:
#Workbook.copy_worksheet() method:
source = wb.active
target = wb.copy_worksheet(source)
"""
Note
Only cells (including values, styles, hyperlinks and comments) and certain
worksheet attribues (including dimensions, format and properties) are copied.
All other workbook / worksheet attributes are not copied - e.g. Images, Charts.
You also cannot copy worksheets between workbooks. You cannot copy a worksheet
if the workbook is open in read-only or write-only mode.
"""
#-----------------------------Playing with data
# Accessing one cell---------------------------------------------------------
#Now we know how to get a worksheet, we can start modifying cells content.
# Cells can be accessed directly as keys of the worksheet:
c = ws['A4']
#This will return the cell at A4, or create one if it does not exist yet.
# Values can be directly assigned:
ws['A4'] = 4
#There is also the Worksheet.cell() method.
#This provides access to cells using row and column notation:
d = ws.cell(row=4, column=2, value=10)
print(d)
print(d.value)
d = ws.cell(row=i, column=j, value="{0}".format(title_1))
print(d)
print(d.value)