1.openpyxl寫入數據
例子1:
import openpyxl
f = openpyxl.Workbook()
table = f.active
table['A2'] = 4
table['A1'] = 5
table.cell(row = 3,column = 1,value = 10)
table.cell(row = 4,column = 1, value = 11)
# 添加一列數據
row = [1,2,3,4,5]
for i in row:
table.append([i])
# 添加多行
rows = [
['Number', 'data1', 'data2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
]
for row in rows:
table.append(row)
#添加一列數據
values = ['abc','edfe', 'apples', 'bananas']
for item in values:
table.append([item])
f.template = True
f.save('data/demo.xlsx')
例子2:
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
wb = Workbook()
ws = wb.active
data = [
['Apples', 10000, 5000, 8000, 6000],
['Pears', 2000, 3000, 4000, 5000],
['Bananas', 6000, 6000, 6500, 6000],
['Oranges', 500, 300, 200, 700],
]
# add column headings. NB. these must be strings
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table1", ref="A1:E5")
# Add a default style with striped rows and banded columns
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save("data/table.xlsx")
txt文件轉換爲xlsx
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 19:34:06 2019
@author: admin
"""
import openpyxl
def txt2xlsx(texts,output):
f = openpyxl.Workbook()
table = f.active
for text in texts:
table.append([text])
f.template = True
f.save(output)
def read_text_src(text_src, delimiter):
if isinstance(text_src, str):
with open(text_src, 'r',encoding = 'utf-8') as f:
text_src = [line.split(delimiter) for line in f]
elif not isinstance(text_src, list):
raise TypeError('text_src should be list or str')
return text_src
name = 'rg_train_20190102_20181227114134'
file_train = '%s.train'%name
output = 'data/%s.xlsx'%name
text_src = read_text_src(file_train, ":")
texts = []
for line in text_src:
texts.append(line[6])
txt2xlsx(texts,output)
2.openpyxl讀取數據
from openpyxl import load_workbook
wb = load_workbook('data/demo.xlsx')
#print(wb.get_sheet_names())
#a_sheet = wb.get_sheet_by_name('Sheet')
#print(a_sheet.title)
sheet = wb.active
b4 = sheet['A4']
print(b4.value)
b4_too = sheet.cell(row = 4,column = 1)
print(b4_too.value)
# =============================================================================
# # A1, A2, A3這樣的順序
# for column in sheet.columns:
# for cell in column:
# print(cell.value)
# =============================================================================
#讀取一列數據
for cell in list(sheet.columns)[0]:
print(cell.value)
可參考博客:https://www.cnblogs.com/sun-haiyu/p/7096423.html