使用python读Excel文件并写入另一个xls模版

这篇具有很好参考价值的文章主要介绍了使用python读Excel文件并写入另一个xls模版。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

效果如下:

原文件内容

使用python读Excel文件并写入另一个xls模版,python,数据库,开发语言

转化后的内容

使用python读Excel文件并写入另一个xls模版,python,数据库,开发语言

大致代码如下:

1. load_it.py

#!/usr/bin/env python
import re
from datetime import datetime
from io import BytesIO
from pathlib import Path
from typing import List, Union

from fastapi import HTTPException
from openpyxl import load_workbook

RE_SPACES = re.compile(r"\s{2,}")


def slim(s: str) -> str:
    return RE_SPACES.sub(" ", s)


class ValidationError(HTTPException):
    def __init__(self, detail: str, status_code: int = 400):
        super().__init__(status_code, detail=detail)


def remove_author(s: str) -> str:
    if s := s.replace("作者:\n", "").replace("Administrator:\n", ""):
        return str(s)
    return ''


def read_excel(filename: Union[Path, str, bytes, BytesIO]):
    if isinstance(filename, bytes):
        filename = BytesIO(filename)
    return load_workbook(filename)


def load(filename: Union[Path, str, bytes, BytesIO]):
    wb = read_excel(filename)
    sheet_name = "工资表"
    try:
        sheet = wb[sheet_name]
    except KeyError:
        try:
            sheet = wb["Sheet1"]
        except KeyError:
            raise ValidationError(f"未找到名称为{sheet_name!r}的工作表")
    title = sheet.cell(1, 1).value.strip()
    now = datetime.now()
    if "月" in title:
        remark = title.split("年")[-1].strip("表").replace("份", "")
    else:
        if (month := now.month - 1) == 0:
            month = 12
        remark = f"{month}月工资"
    day = f"{now:%Y.%m.%d}"
    lines: List[list] = []
    for row in range(4, sheet.max_row):
        xuhao = sheet.cell(row, 1).value
        if xuhao and (isinstance(xuhao, int) or xuhao.isdigit()):
            name = sheet.cell(row, 2).value
            total = 0
            if (base := sheet.cell(row, 4).value) is None:
                base = "/"
            else:
                if isinstance(base, str):
                    if base.startswith("="):
                        base = eval(base[1:])
                    else:
                        raise TypeError(f"Expect int value, got: {base=}")
                total += base
            commission_comment = ""  # 提成批注
            commission_cell = sheet.cell(row, 5)
            if (commission := commission_cell.value) is None:
                commission = "/"
            else:
                if isinstance(commission, str) and commission.startswith('='):
                    commission = eval(commission[1:])
                total += commission
                if _cc := commission_cell.comment:
                    if _ct := _cc.text:
                        commission_comment = remove_author(_ct)
            if (attend := sheet.cell(row, 6).value) is None:
                if (attend := sheet.cell(row, 13).value) is None:
                    attend = "/"
            if (attend_money := sheet.cell(row, 7).value) is not None:
                total += attend_money
                attend = attend.strip().strip("+-/").strip()
                if attend_money > 0:
                    attend += f" +{attend_money}"
                else:
                    attend += f" {attend_money}"
            if (late := sheet.cell(row, 8).value) is None:
                late = "/"
            else:
                late = slim(late)
            if late_money := sheet.cell(row, 9).value:
                total += late_money
                if late_money > 0:
                    late = f"{late}{late_money}"
                else:
                    late = late.strip("/") + str(late_money)
            if subsidy_value := sheet.cell(row, 11).value:  # 补助
                if isinstance(subsidy_value, str) and subsidy_value.startswith("="):
                    subsidy_value = eval(subsidy_value[1:])
                try:
                    total += subsidy_value
                except TypeError:
                    raise ValidationError(
                        f"第{row}行第11列数据异常:预期为数值,得到的是{subsidy_value!r}"
                    )
            subsidy = "/"
            if _c := sheet.cell(row, 10).comment:
                if _s := _c.text:
                    subsidy = remove_author(_s)

            one = [
                name,
                base,
                commission,
                attend,
                late,
                subsidy,
                total,
                remark,
                day,
                commission_comment,
            ]
            lines.append(one)
    return lines


def main():
    import sys

    if not sys.argv[1:]:
        print("No args, do nothing.")
        return
    print(load(sys.argv[1]))


if __name__ == "__main__":
    main()

 

 2. gen_excel.py

#!/usr/bin/env python
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Tuple, Union

import xlrd
import xlwt
from xlutils.copy import copy as xls_copy

from load_it import load, read_excel, remove_author
from settings import BASE_DIR, MEDIA_ROOT

SAMPLE = "salary_tips.xls"
DataType = Union[int, float, str, None]


def cell_style(is_top: bool = False, is_bottom: bool = False, has_border=True):
    """单元格样式"""
    style = xlwt.XFStyle()
    # 字体大小,11为字号,20为衡量单位
    # font = xlwt.Font()
    style.font.height = 20 * 9

    align = xlwt.Alignment()
    # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
    align.horz = 0x02
    # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
    align.vert = 0x01
    # 设置自动换行
    align.wrap = 1
    style.alignment = align

    # 设置边框
    # 细实线:1,小粗实线:2,细虚线:3,中细虚线:4,大粗实线:5,双线:6,细点虚线:7
    # 大粗虚线:8,细点划线:9,粗点划线:10,细双点划线:11,粗双点划线:12,斜点划线:13
    if has_border:
        borders = xlwt.Borders()
        borders.left = 2
        borders.right = 2
        borders.top = 1 + is_top
        borders.bottom = 1 + is_bottom
        style.borders = borders
    return style


def boom(tips: List[List[Tuple[int, int, DataType]]]) -> str:
    """将数据填入模板生成Excel表"""
    sample = BASE_DIR / SAMPLE
    xls = xls_copy(xlrd.open_workbook(sample, formatting_info=True))
    ws = xls.get_sheet(0)
    style = cell_style()
    top_style = cell_style(is_top=True)
    bottom_style = cell_style(is_bottom=True)
    plain_style = cell_style(has_border=False)
    last_index = 8
    for datas in tips:
        for i, d in enumerate(datas[:-1]):
            if i == 0:
                ws.write(*d, top_style)
            elif i == last_index:
                ws.write(*d, bottom_style)
            else:
                ws.write(*d, style)
        if _tc := datas[-1]:
            row, col, text = _tc
            if text:
                ws.write_merge(row, row, col - 1, col, text, plain_style)
    fname = MEDIA_ROOT / f"gzt_{datetime.now():%Y%m%d%H%M%S}.xls"
    try:
        xls.save(fname)
    except TypeError as e:
        print("May be you can look at this to fix it:")
        print("https://blog.csdn.net/zhangvalue/article/details/105170305")
        raise e
    return str(fname).replace(str(BASE_DIR), "")  # 返回相对路径


def build_tips(lines: List[List[DataType]]):
    row_delta = 10  # 每隔10行填下一排的数据
    col_delta = 3  # 每隔3列填下一组数据
    line_tip = 5  # 每行有5个工资条
    row_begin = 0  # 从第一行开始
    col_begin = 1  # 从第二列开始填数据(第一列是固定的表头)
    tips = []
    for tip_index, tip in enumerate(lines):
        first_row = row_begin + tip_index // line_tip * row_delta
        col_index = col_begin + tip_index % line_tip * col_delta
        d = [
            (row_index + first_row, col_index, value)
            for row_index, value in enumerate(tip)
        ]
        tips.append(d)
    return tips


def burn_life(content: bytes) -> str:
    return boom(build_tips(load(content)))


def dear_sister(content: bytes, origin_name: Optional[str] = None) -> str:
    """2022-04-04 亲爱的妹妹想要一个可以把批注提取出来的"""
    wb = read_excel(content)
    sheet = wb.worksheets[0]
    count = 0
    # openpyxl的行和列都是从1开始
    for row in range(1, sheet.max_row):
        for col in range(1, sheet.max_column):
            cell = sheet.cell(row, col)
            if comment := cell.comment:
                if text := comment.text:
                    cell.value = remove_author(text)
                    count += 1
    if origin_name:
        fname = MEDIA_ROOT / f"{Path(origin_name).stem}-批注提取{count}.xls"
    else:
        fname = MEDIA_ROOT / f"批注提取{count}.xls"
    wb.save(fname)
    return str(fname).replace(str(BASE_DIR), "")  # 返回相对路径


def main():
    import sys

    if not sys.argv[1:]:
        print("No args, do nothing.")
        return
    if (p := Path(sys.argv[1])).is_file():
        lines = load(p.read_bytes())
    else:
        day = f"{datetime.now():%Y.%m.%d}"
        ss = [
            "狄仁杰",
            1600,
            360,
            "休5天,请假7.5天 -400",
            "迟到3次共16分钟",
            "扣社保-373\n工龄+100\n漏刷卡6次-300",
            987,
            "12月工资",
            day,
        ]
        lines = [ss, ss]
    print(boom(build_tips(lines)))


if __name__ == "__main__":
    main()

    文章来源地址https://www.toymoban.com/news/detail-653191.html

到了这里,关于使用python读Excel文件并写入另一个xls模版的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 【Python】将数据写入excel文件中

    【Python】将数据写入excel文件中

    python实现将数据写入excel文件中。 1、导入依赖包xlwt 注意:这里的xlwt是python的第三方模块,需要下载安装才能使用(如果没安装可直接在终端输入pip install xlwt进行安装)。 2、创建excel表格类型文件 3、在excel表格类型文件中建立一张sheet表单 4、将指定值写入sheet 5、保存exc

    2024年02月12日
    浏览(49)
  • Python读取写入数据到Excel文件

    Python读取写入数据到Excel文件

    【Linux干货教程】Ubuntu Linux 换源详细教程 大家好,我是洲洲,欢迎关注,一个爱听周杰伦的程序员。关注公众号【程序员洲洲】即可获得10G学习资料、面试笔记、大厂独家学习体系路线等…还可以加入技术交流群欢迎大家在CSDN后台私信我! Hello,各位看官老爷们好,洲洲已

    2024年02月12日
    浏览(53)
  • 用python将数据写入Excel文件中

    用python将数据写入Excel文件中

    1、导入第三方库 xlwt 2、调用xlwt模块中的Workbook方法来创建一个excel表格类型文件,其中的第一个参数是设置数据的编码格式,这里是’utf-8’的形式,style_compression设置是否压缩,不是很常用,赋值为0表示不压缩。 3、用wb对象调用add_sheet方法来建立一张sheet表,这里面的第一

    2024年02月15日
    浏览(48)
  • Python 将列表数据写入文件(txt, csv,excel)

    Python 将列表数据写入文件(txt, csv,excel)

    将数据写入新文件 将数据写入第 i 行,第 j 列

    2024年01月16日
    浏览(209)
  • [excel与dict] python 读取excel内容并放入字典、将字典内容写入 excel文件

    一 读取excel内容、并放入字典 1 读取excel文件 2 读取value,舍弃行号 3 读取为字典 一 读取excel内容、并放入字典(完整代码) 二、将字典内容写入 excel文件 1 假设已有字典内容为: 即student列表里有4个字典, 第一个字典里面有3对key-value \\\"num\\\": 1, \\\"name\\\": \\\"cod1\\\", \\\"wfm\\\": 0.1 2 导入Workb

    2024年02月04日
    浏览(18)
  • 如何使用Python给Excel写入数据

    如何使用Python给Excel写入数据

    openpyxl三步走 获取work book 获取 work sheet 再然后 获取单元格 进行操作 保存文件 安装OpenpyXl 导包方式以下两种都可以 from openpyxl import Workbook from openpyxl import load_workbook 向工作表中写入数据 保存至文件 最保险的保存方式是调用 save 方法保存到指定文件: 结果如下: 向工作表中

    2024年02月14日
    浏览(11)
  • 使用 Python 数据写入 Excel 工作表

    使用 Python 数据写入 Excel 工作表

    在数据处理和报告生成等工作中,Excel 表格是一种常见且广泛使用的工具。然而,手动将大量数据输入到 Excel 表格中既费时又容易出错。为了提高效率并减少错误,使用 Python 编程语言来自动化数据写入 Excel 表格是一个明智的选择。Python 作为一种简单易学且功能强大的编程

    2024年01月18日
    浏览(13)
  • 使用Python写入数据到Excel:实战指南

    使用Python写入数据到Excel:实战指南

    在数据科学领域,Excel是一种广泛使用的电子表格工具,可以方便地进行数据管理和分析。然而,当数据规模较大或需要自动化处理时,手动操作Excel可能会变得繁琐。此时,使用Python编写程序将数据写入Excel文件是一个高效且便捷的选择。本文将介绍如何使用Python将数据写入

    2024年02月11日
    浏览(17)
  • 使用 Python 将数据写入 Excel 工作表

    使用 Python 将数据写入 Excel 工作表

    在数据处理和报告生成等工作中,Excel 表格是一种常见且广泛使用的工具。然而,手动将大量数据输入到 Excel 表格中既费时又容易出错。为了提高效率并减少错误,使用 Python 编程语言来自动化数据写入 Excel 表格是一个明智的选择。Python 作为一种简单易学且功能强大的编程

    2024年02月01日
    浏览(10)
  • VBA:Application.GetOpenFilename打开指定文件夹里的excel类型文件(xls、xlsx)

    \\\'GetOpenFilename相当于Excel打开窗口,通过该窗口选择要打开的文件,并可以返回选择的文件完整路径和文件名。 \\\'Application.GetOpenFilename(“文件类型筛选规则(就是说明)”,“优先显示第几个类型的文件”,“标题”,“是否允许选择多个文件名”) 打开类型只限excel文件 \\\'“文件类型

    2024年02月11日
    浏览(10)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包