openpyxl module and csv module

openpyxl module and csv module

foreword

   A csv file is a plain text file separated by commas, while an Excel file is a spreadsheet file generated by Microsoft Office software. The csv format stores data, which is more convenient to read and write, easy to implement, and the file will be smaller than the Excel file. However, CSV files only provide simple data storage functions, and Excel files have rich analysis and calculation functions. The openpyxl module is used for data manipulation of xlsx files, while the csv module is used for csv files.


1. openpyxl module

1 Introduction

   openpyxl is a third-party python library for processing Excel spreadsheet files in xlsx format, which supports most basic operations of Excel spreadsheets. To install, use the pip install openpyxl command.

2. Method

(1) File writing method, Workbook()

from openpyxl import Workbook,load_workbook

# Workbook()函数创建新的workbook(工作簿)对象,就是创建新的空的Excel文件。
wb = Workbook()
# wb.active就是获取这个工作簿的活动表,通常就是第一个工作表。
#创建完新的工作簿后,还得获取工作表。不然程序会无所适从,不知道要把内容写入哪张工作表里
ws = wb.active
#使用title给工作表重命名
ws.title = 'newSheet' 
# 添加完工作表,可以操作单元格,往单元格添加东西
ws['A1'] = '神话故事'
# 把我们想有写入的内容写成列表,赋值给row
row = ['盘古',"女娲","夸父"]
# 使用ws.append()往表格里添加这一行文字,append为添加,列表一个元素为一个单元格
ws.append(row)

# 先把要写入的多行内容写成列表,再放大进入大列表里,赋值给rows
rows = [['盘古',"女娲","夸父"],['是','神话','故事', '经典','人物']]
for i in rows:
    ws.append(i)
print(rows)
a = [1,2,3,4]
b = ["A","B","C","D"]
c = ["!","@","#","$"]
#添加列名
ws.append(['a','b','c'])
#使用为zip函数把多个列表的值进行迭代合并
for i in list(zip(a,b,c)):
    ws.append(i)

# 保存新建的Excel文件,并命名为“Myth.xlsx”
wb.save('C:/Users/tang/Desktop/Myth.xlsx')

(2) File reading method, load_workbook()

#使用load_workbook()函数,该方法中还有一个 read_only 参数用于设置文件打开方式。
#默认为可读可写,该方法最终将返回一个 workbook 的数据对象
wb = load_workbook('C:/Users/tang/Desktop/Myth.xlsx')
ws = wb['newSheet'] 
#sheetnames是用来获取工作簿所有工作表的名字的。
#如果你不知道工作簿到底有几个工作表,就可以把工作表的名字都打印出来。
sheetname = wb1.sheetnames
print(sheetname)
#1. 获取A1单元格的值
A1_cell = ws['A1']
A1 = A1_cell.value
# 2.通过sheet.cell(row,column)获取,即sheet('A2')
A2_cell = ws.cell(2,1)
A2 = A2_cell.value
# 3.获取单元格所在行和列
print((A2_cell.row,A2_cell.column))
#4.对行进行遍历
for row in ws.rows:
    for cell in row:
        print(cell.value)
# 5.对列进行遍历
for column in ws.columns:
    for cell in column:
        print(cell.value)
# 6.对特定范围进行遍历,如获取第一行的值
for cell in list(ws.rows)[0]:
    print(cell.value)
# 7.对某一单元格的范围进行遍历:
for spaces in sheet['A1':'B2']:  #获取A1,A2,B1,B2的值
    for cell in spaces:
        print(cell.value)
# 8.通过max_row 和 max_column 来获取获取表格行和列的数量
print(ws.max_row)
print(ws.max_column)
#在读取文件时需要加上参数 data_only=True ,这样才能返回数字,
#否则将返回字符串,即公式本身
# 直接赋值
sheet['A1'].value = 2
# 公式赋值
sheet['A6'].value = '=SUM(A1:A5)'

(3) Adjustment of font, border and color

# 导入字体、边框、颜色以及对齐方式相关库
from openpyxl.styles import Font, Border, Side, PatternFill, colors, Alignment

# 1.通过 sheet 单元格 font 属性设置字体风格
# 设置字体风格为Times New Roman,大小为16,粗体、斜体,颜色蓝色
sheet['A1'].font = Font(name='Times New Roman', size=16, bold=True, italic=True, color=colors.BLUE)
# 2.通过 sheet 单元格 alignment 属性设置文本对齐风格
# 通过参数horizontal和vertical来设置文字在单元格里的对齐方式,此外设置值还可为left和right
sheet['B1'].alignment = Alignment(horizontal='center',vertical='center')

Two, csv module

1 Introduction

    ​ CSV (Comma Separated Values) is a comma-separated text format, which is often used for importing and exporting Excel and databases. Python's built-in CSV module provides objects for reading and writing CSV format files.


2. Method

(1) Write to writer()

import csv

rows=[("铅笔","20"),("毛笔","21"),("钢笔","22")]
# 调用open()函数打开csv文件,传入参数:文件名“demo.csv”、
# 写入模式“w”、newline=''、encoding='utf-8'。
with open('demo.csv','w',newline='',encoding='utf-8') as f:
	# 1.用csv.writer()函数创建一个writer对象
	writer = csv.writer(f)
	# 2.调用writer对象的writerrow()方法,可以在csv文件里写入一行文字
	writer.writerow(['电影',"豆瓣评分"])
	writer.writerow(['银河护卫队','8.0'])
	writer.writerow(['复仇者联盟','8.1'])
	#3.多行写入
    w.writerows(rows)
# 写入完成,关闭文件
f.close()

#只能读取原文件render,修改所对应的列的值,写入新的文件中
reader = csv.reader(in_file)
out_file = open("d:/out.csv", "wb")
writer = csv.writer(out_file)
for row in reader:
    row[3] = 4
    writer.writerow(row)
out_file.close()
#修改特点的单元格
 f = open('mylist.csv', 'r')
 reader = csv.reader(f)
 mylist = list(reader)
 f.close()
 mylist[1][3] = 'X'
 my_new_list = open('mylist.csv', 'w', newline = '')
 csv_writer = csv.writer(my_new_list)
 csv_writer.writerows(mylist)
 my_new_list.close()

(2) Read reader()

with open('demo.csv', 'r', newline='', encoding='utf-8') as f:
	# 1.用csv.reader()函数创建一个reader对象
    reader = csv.reader(f)
    #2.遍历打印每一行
    for r in reader:
        print(r)      
# 数据
No.,Name,Age,Score
1,Apple,12,98
2,Ben,13,97
3,Celia,14,96
4,Dave,15,95
with open('A.csv','rb') as csvfile:
    reader = csv.reader(csvfile)
    rows = [row for row in reader]   
print(rows) 	
[['No.', 'Name', 'Age', 'Score'],
['1', 'Apple', '12', '98'],
['2', 'Ben', '13', '97'],
['3', 'Celia', '14', '96'],
['4', 'Dave', '15', '95']]
#1.读取csv文件的某一行
    for i,rows in enumerate(reader):
        if i == 2:
            row = rows            
print (row) 
['2', 'Ben', '13’', '97']
#2.读取csv文件的某一列
	column = [row[2] for row in reader]
	print(column)
['Age', '12', '13', '14', '15']

3.csv read and write mode

(1)r:以读方式打开文件,可读取文件信息
(2)w: 已写方式打开文件,可向文件写入信息。如文件存在,则清空,再写入
(3)a:以追加模式打开文件,打开文件可指针移至末尾,文件不存在则创建
(4)r+:以读写方式打开文件,可对文件进行读和写操作
(5)w+:消除文件内容,以读写方式打开文件
(6)a+:以读写方式打开文件,文件指针移至末尾
(7)b:以二进制打开文件

Guess you like

Origin blog.csdn.net/tang5615/article/details/129481873