当前位置:   article > 正文

python xlsx读写实践_python 读取xlsx文件

python 读取xlsx文件

1 读xlsx

get_data_from_xlsx()函数中,将file指向的.xlsx文件读取到data中,并作为返回值。

数据准备,在该tmp.py文件下,有一个example.xlsx文件,它的内容为,
在这里插入图片描述

图1 example.xlsx文件内容展示

读取代码如下(tmp.py文件内容),

import copy
import lxml
from openpyxl import Workbook
from openpyxl import load_workbook

def get_data_from_xlsx(file: str) -> list[list[str]]:
    wb = load_workbook(file)
    sheets = wb.worksheets #获取当前所有的sheet
    sheet = sheets[0] #只有第1个sheet的信息才有用
    data = []
    for row in sheet:
        row = [x.value for x in row]
        data.append(copy.deepcopy(row))
    return copy.deepcopy(data)
inputpath = '.\\example.xlsx'
data = get_data_from_xlsx(inputpath)    
for row in data:
    print(row)
print('程序执行成功!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

代码输出为,

['姓名', '性别', '学号', '班级']
['小明', '男', '001', '一班']
['小军', '男', '002', '一班']
['小红', '女', '003', '一班']
程序执行成功!
  • 1
  • 2
  • 3
  • 4
  • 5

2 写xlsx

write_data_to_xlsx()函数中,将data中的信息写入到path指向的文件中。

import copy
import lxml
from openpyxl import Workbook
from openpyxl import load_workbook

def write_data_to_xlsx(path: str, data: list[list[str]], head: list[str])->None:
    wb = Workbook()
    ws = wb.active
    ws.append(head)
    for row in data:
        if not isinstance(row, list): #如果x不是列表类型,则将其变为列表类型
            row = [row]
        ws.append(row)
    wb.save(path)
    return

data = [['小明', '男', '001', '一班'], ['小军', '男', '002', '一班'], ['小红', '女', '003', '一班']]
head = ['姓名', '性别', '学号', '班级']
path = '.\\output.xlsx'
write_data_to_xlsx(path, data, head)
print('程序执行成功!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

程序运行结果,
在这里插入图片描述

图2 运行结果展示图

output.xlsx文件内容为,
在这里插入图片描述

图3 output.xlsx内容展示

创建新工作表的python3代码示例,主要是这个ws = wb.create_sheet(title=sheet_name)

def WriteXlsx(path: str, data: list[list[str]], head: str, sheet_name: str)->None:
    wb = Workbook()
    ws = wb.create_sheet(title=sheet_name) #通过sheet_name创建新工作表
    
    ws.append(head)
    for x in data:
        #print(f'x = {x})
        ws.append(x)
    wb.save(path)
    return
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
'
运行
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/816996
推荐阅读
相关标签
  

闽ICP备14008679号