国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

使用python讀Excel文件并寫入另一個xls模版

這篇具有很好參考價值的文章主要介紹了使用python讀Excel文件并寫入另一個xls模版。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

效果如下:

原文件內(nèi)容

使用python讀Excel文件并寫入另一個xls模版,python,數(shù)據(jù)庫,開發(fā)語言

轉(zhuǎn)化后的內(nèi)容

使用python讀Excel文件并寫入另一個xls模版,python,數(shù)據(jù)庫,開發(fā)語言

大致代碼如下:

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列數(shù)據(jù)異常:預期為數(shù)值,得到的是{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:
    """將數(shù)據(jù)填入模板生成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行填下一排的數(shù)據(jù)
    col_delta = 3  # 每隔3列填下一組數(shù)據(jù)
    line_tip = 5  # 每行有5個工資條
    row_begin = 0  # 從第一行開始
    col_begin = 1  # 從第二列開始填數(shù)據(jù)(第一列是固定的表頭)
    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()

? ??文章來源地址http://www.zghlxwxcb.cn/news/detail-653191.html

到了這里,關于使用python讀Excel文件并寫入另一個xls模版的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 【Python】將數(shù)據(jù)寫入excel文件中

    【Python】將數(shù)據(jù)寫入excel文件中

    python實現(xiàn)將數(shù)據(jù)寫入excel文件中。 1、導入依賴包xlwt 注意:這里的xlwt是python的第三方模塊,需要下載安裝才能使用(如果沒安裝可直接在終端輸入pip install xlwt進行安裝)。 2、創(chuàng)建excel表格類型文件 3、在excel表格類型文件中建立一張sheet表單 4、將指定值寫入sheet 5、保存exc

    2024年02月12日
    瀏覽(96)
  • Python讀取寫入數(shù)據(jù)到Excel文件

    Python讀取寫入數(shù)據(jù)到Excel文件

    【Linux干貨教程】Ubuntu Linux 換源詳細教程 大家好,我是洲洲,歡迎關注,一個愛聽周杰倫的程序員。關注公眾號【程序員洲洲】即可獲得10G學習資料、面試筆記、大廠獨家學習體系路線等…還可以加入技術交流群歡迎大家在CSDN后臺私信我! Hello,各位看官老爺們好,洲洲已

    2024年02月12日
    瀏覽(97)
  • 用python將數(shù)據(jù)寫入Excel文件中

    用python將數(shù)據(jù)寫入Excel文件中

    1、導入第三方庫 xlwt 2、調(diào)用xlwt模塊中的Workbook方法來創(chuàng)建一個excel表格類型文件,其中的第一個參數(shù)是設置數(shù)據(jù)的編碼格式,這里是’utf-8’的形式,style_compression設置是否壓縮,不是很常用,賦值為0表示不壓縮。 3、用wb對象調(diào)用add_sheet方法來建立一張sheet表,這里面的第一

    2024年02月15日
    瀏覽(90)
  • Python 將列表數(shù)據(jù)寫入文件(txt, csv,excel)

    Python 將列表數(shù)據(jù)寫入文件(txt, csv,excel)

    將數(shù)據(jù)寫入新文件 將數(shù)據(jù)寫入第 i 行,第 j 列

    2024年01月16日
    瀏覽(435)
  • [excel與dict] python 讀取excel內(nèi)容并放入字典、將字典內(nèi)容寫入 excel文件

    一 讀取excel內(nèi)容、并放入字典 1 讀取excel文件 2 讀取value,舍棄行號 3 讀取為字典 一 讀取excel內(nèi)容、并放入字典(完整代碼) 二、將字典內(nèi)容寫入 excel文件 1 假設已有字典內(nèi)容為: 即student列表里有4個字典, 第一個字典里面有3對key-value \\\"num\\\": 1, \\\"name\\\": \\\"cod1\\\", \\\"wfm\\\": 0.1 2 導入Workb

    2024年02月04日
    瀏覽(32)
  • 如何使用Python給Excel寫入數(shù)據(jù)

    如何使用Python給Excel寫入數(shù)據(jù)

    openpyxl三步走 獲取work book 獲取 work sheet 再然后 獲取單元格 進行操作 保存文件 安裝OpenpyXl 導包方式以下兩種都可以 from openpyxl import Workbook from openpyxl import load_workbook 向工作表中寫入數(shù)據(jù) 保存至文件 最保險的保存方式是調(diào)用 save 方法保存到指定文件: 結(jié)果如下: 向工作表中

    2024年02月14日
    瀏覽(20)
  • 使用 Python 數(shù)據(jù)寫入 Excel 工作表

    使用 Python 數(shù)據(jù)寫入 Excel 工作表

    在數(shù)據(jù)處理和報告生成等工作中,Excel 表格是一種常見且廣泛使用的工具。然而,手動將大量數(shù)據(jù)輸入到 Excel 表格中既費時又容易出錯。為了提高效率并減少錯誤,使用 Python 編程語言來自動化數(shù)據(jù)寫入 Excel 表格是一個明智的選擇。Python 作為一種簡單易學且功能強大的編程

    2024年01月18日
    瀏覽(23)
  • 使用 Python 將數(shù)據(jù)寫入 Excel 工作表

    使用 Python 將數(shù)據(jù)寫入 Excel 工作表

    在數(shù)據(jù)處理和報告生成等工作中,Excel 表格是一種常見且廣泛使用的工具。然而,手動將大量數(shù)據(jù)輸入到 Excel 表格中既費時又容易出錯。為了提高效率并減少錯誤,使用 Python 編程語言來自動化數(shù)據(jù)寫入 Excel 表格是一個明智的選擇。Python 作為一種簡單易學且功能強大的編程

    2024年02月01日
    瀏覽(22)
  • 使用Python寫入數(shù)據(jù)到Excel:實戰(zhàn)指南

    使用Python寫入數(shù)據(jù)到Excel:實戰(zhàn)指南

    在數(shù)據(jù)科學領域,Excel是一種廣泛使用的電子表格工具,可以方便地進行數(shù)據(jù)管理和分析。然而,當數(shù)據(jù)規(guī)模較大或需要自動化處理時,手動操作Excel可能會變得繁瑣。此時,使用Python編寫程序?qū)?shù)據(jù)寫入Excel文件是一個高效且便捷的選擇。本文將介紹如何使用Python將數(shù)據(jù)寫入

    2024年02月11日
    瀏覽(36)
  • VBA:Application.GetOpenFilename打開指定文件夾里的excel類型文件(xls、xlsx)

    \\\'GetOpenFilename相當于Excel打開窗口,通過該窗口選擇要打開的文件,并可以返回選擇的文件完整路徑和文件名。 \\\'Application.GetOpenFilename(“文件類型篩選規(guī)則(就是說明)”,“優(yōu)先顯示第幾個類型的文件”,“標題”,“是否允許選擇多個文件名”) 打開類型只限excel文件 \\\'“文件類型

    2024年02月11日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包