python实现excel的写入和读出

python实现excel的写入和读出

缘起:

工作换到另一个城市,来到后需要隔离14天,早就想使用py作为日常工具使用,作为java开发者,java虽然用起来最顺手,但是作为工具语言显然不合适,py作为解释型语言和胶水语言,又作为linux系统默认继承的环境,比较适合作为工具,我目前对它有3个要求

  1. 作为一门快速出项目的语言,搭上框架就可以简单的撸一个http服务,个人有一个云服务器,配置只有1核CPU和2G内存,装个jvm跑个Tomcat,估计负载就到顶了,而且java不适合快速出项目
  2. 作为操作Excel的工具使用,Excel会遇到复杂的操作场景,个人Excel玩的并不好,但是可以用编程弥补
  3. 作为数据库修复数据的工具使用,有时候因为bug需要人工修复数据,sql玩的没那么好,可以用趁手的语言作为工具来弥补

源码 请原谅我写出了java风格的python代码

首先要安装两个包xlrdxlwt,前者是excel读相关的包,全名是excel read,后者是excel写相关的包,全名是excel write,安装:

pip install xlrd
pip install xlwt

读相关:

# ReadExcel.py
import xlrd
from typing import List


def readWorkBook(path: str) -> xlrd.Book:
    try:
        book = xlrd.open_workbook(path)
    except xlrd.XLRDError as error:
        print(error)
        return None
    else:
        return book


def readData(book: xlrd.Book, sheetIndex: int) -> List[List[str]]:
    sheet = book.sheet_by_index(sheetIndex)
    data = list(list())
    for i in range(0,sheet.nrows):
        data.append(sheet.row_values(i))

    return data

写相关:

# WriteExcel.py

import xlwt
from typing import List


# 实例化工作簿
def createWorkBook() -> xlwt.Workbook:
    return xlwt.Workbook()


def createSheet(book: xlwt.Workbook, sheetName: str) -> xlwt.Worksheet:
    return book.add_sheet(sheetname=sheetName, cell_overwrite_ok=True)


def writeData(sheet: xlwt.Worksheet, array: List[List[str]]) -> None:
    i = j = 0
    for x in array:
        for y in x:
            sheet.write(i, j, y)
            j += 1
        i += 1
        j = 0


def save(book: xlwt.Workbook, path: str) -> None:
    book.save(path)

测试:

# ExcelTest.py

import WriteExcel
import ReadExcel
import time


def formatTimeNow() -> str:
    now = int(time.time())
    localTime = time.localtime(now)
    return time.strftime('%Y-%m-%d %H:%M:%S', localTime)


EXCEL_FILE_PATH = '/Volumes/mac/test.xls'


def testWrite() -> None:
    book = WriteExcel.createWorkBook()
    sheet = WriteExcel.createSheet(book, 'test1')

    lst = [
        ['序号', '姓名', '性别', '出生日期', '填表日期']
    ]

    for i in range(1, 10):
        newList = [
            i, 'blf' + str(i), '男' if (i & 1) == 1 else '女', '1994-08-' + '0' + str(i), formatTimeNow()
        ]
        lst.append(newList)

    WriteExcel.writeData(sheet, lst)

    WriteExcel.save(book, EXCEL_FILE_PATH)


def testRead() -> None:
    book = ReadExcel.readWorkBook(EXCEL_FILE_PATH)

    if not(book is None):
        print(ReadExcel.readData(book, 0))


testWrite()
testRead()

代码相对简单,需要在python3.5版本以上运行,因为有类型标记,写完我自己都笑了,感觉java风格深入我心,下面是测试结果:
python实现excel的写入和读出_第1张图片
读取是这样的:

[['序号', '姓名', '性别', '出生日期', '填表日期'], [1.0, 'blf1', '男', '1994-08-01', '2020-03-06 15:45:58'], [2.0, 'blf2', '女', '1994-08-02', '2020-03-06 15:45:58'], [3.0, 'blf3', '男', '1994-08-03', '2020-03-06 15:45:58'], [4.0, 'blf4', '女', '1994-08-04', '2020-03-06 15:45:58'], [5.0, 'blf5', '男', '1994-08-05', '2020-03-06 15:45:58'], [6.0, 'blf6', '女', '1994-08-06', '2020-03-06 15:45:58'], [7.0, 'blf7', '男', '1994-08-07', '2020-03-06 15:45:58'], [8.0, 'blf8', '女', '1994-08-08', '2020-03-06 15:45:58'], [9.0, 'blf9', '男', '1994-08-09', '2020-03-06 15:45:58']]

记录一下,以后有excel的需求,直接可以参考此博客

你可能感兴趣的:(python)