租房水电费发票账单自动生成系统设计与实现,已封装的windows可直接运行,无需手写,直接1秒自动生成,后附源码

一、项目展示

系统页面(两个按钮简单操作)

按钮一:上传模板文件 并保存数据

一、首先输入模板文件内容(格式如下为:房间号、上月水使用额度、上月电使用额度、本月水使用额度、本月电使用额度)

二、打开写好的模板文件(目前用111.xlsx代替)

三、自动另存为数据文件(这里设置文件名为222.xlsx,生成数据如下)

按钮二、使用数据文件生成发票

一、选中前面生成的222.xlsx

二、发票收据自动生成(自动生成excel发票文件)

打开如下(文件名自动生成为:今日时间+水电费发票)

项目文件(如下图所示)

二、源码

import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox
from openpyxl import load_workbook
from datetime import datetime

def calculate_cost(df):
    water_rate = 6.0  # 每吨水的费用
    electricity_rate = 1.2  # 每千瓦时电的费用
    # hyg_rate = 10.0  # 每月卫生费

    # 计算水费
    df['用水'] = (df['Current Water Usage'] - df['Previous Water Usage']).round(1)
    df['水费'] = df['用水'] * water_rate

    # 计算电费
    df['用电'] = (df['Current Electricity Usage'] - df['Previous Electricity Usage']).round(1)
    df['电费'] = df['用电'] * electricity_rate

    # 卫生费
    # df['卫生费'] = hyg_rate

    # # 读取网络费用
    # if '网络费' not in df.columns:
    #     raise ValueError("Excel 文件中必须包含 '网络费' 列")

    # 总费用
    # df['合计'] = df['水费'] + df['电费'] + df['卫生费'] + df['网络费']
    df['合计'] = df['水费'] + df['电费']  #仅水电费

    return df


def process_excel(input_file, output_file):
    df = pd.read_excel(input_file)

    # 检查所需列
    required_columns = [
        'Room Number', 'Previous Water Usage', 'Previous Electricity Usage',
        'Current Water Usage', 'Current Electricity Usage'
    ]
    if not all(col in df.columns for col in required_columns):
        raise ValueError(f"Excel 文件中必须包含以下列: {', '.join(required_columns)}")

    df = calculate_cost(df)
    df.to_excel(output_file, index=False)


def upload_file():
    input_file = filedialog.askopenfilename(
        filetypes=[("Excel files", "*.xlsx"), ("All files", "*.*")]
    )
    if not input_file:
        return

    output_file = filedialog.asksaveasfilename(
        defaultextension=".xlsx",
        filetypes=[("Excel files", "*.xlsx"), ("All files", "*.*")]
    )
    if not output_file:
        return

    try:
        process_excel(input_file, output_file)
        messagebox.showinfo("成功", f"计算结果已保存到 {output_file}")
    except Exception as e:
        messagebox.showerror("错误", str(e))


def creat_fap():
    # 这里可以添加发票生成的逻辑
    # 定义保存文件名
    datatime_cell = datetime.now().strftime('%Y-%m-%d')
    file_name = f'{datatime_cell}_水电费发票.xlsx'
    # 创建一个新的ExcelWriter对象
    try:
        with pd.ExcelWriter(file_name, engine='xlsxwriter') as writer:
            # 加载表
            # 打开文件选择对话框
            file_path = filedialog.askopenfilename(
                title="选择 Excel 文件",
                filetypes=[("Excel files", "*.xlsx")]
            )

            if file_path:
                # 加载选择的 Excel 文件
                source_wb = load_workbook(file_path)
                source_ws = source_wb.active

                # 继续你的处理代码...
                print("文件已加载:", file_path)
            else:
                print("没有选择文件")

            # 定义开始的行和列
            source_ymh_col = 'A'  # 表1的起始列
            source_swtery_col = 'B'
            source_bwtery_col = 'D'
            source_rwtery_col = 'G'
            source_wtmm_col = 'H'
            source_seey_col = 'C'
            source_beey_col = 'E'
            source_reey_col = 'I'
            source_eemm_col = 'J'
            source_totel_col = 'K'  #对应222表内的行
            # source_net_col = 'F'
            # source_hyg_col = 'K'
            # target_ymh_col = 'B'  # 表2的起始列
            # target_data_col = 'G'

            # 计算表222最大行数
            max_row = source_ws.max_row
            # 将获取的receipt的A2单元格信息写入222的B2单元格
            # target_ws['B2'] = source_ws['A2'].value
            for i in range(2, max_row + 1):
                swfy_cell = f'{source_swtery_col}{i}'  # 上月用水
                swfy_value = f'{source_ws[swfy_cell].value}吨'
                bwfy_cell = f'{source_bwtery_col}{i}'  # 本月用水
                bwfy_value = f'{source_ws[bwfy_cell].value}吨'
                rwfy_cell = f'{source_rwtery_col}{i}'  # 实际用水
                rwfy_value = f'{source_ws[rwfy_cell].value}吨'
                wtmm_cell = f'{source_wtmm_col}{i}'  # 水费
                wtmm_value = f'¥{source_ws[wtmm_cell].value}'
                seey_cell = f'{source_seey_col}{i}'  # 上月用电
                seey_value = f'{source_ws[seey_cell].value}度'
                beey_cell = f'{source_beey_col}{i}'  # 本月用电
                beey_value = f'{source_ws[beey_cell].value}度'
                reey_cell = f'{source_reey_col}{i}'  # 实际用电
                reey_value = f'{source_ws[reey_cell].value}度'
                eemm_cell = f'{source_eemm_col}{i}'  # 电费
                eemm_value = f'¥{source_ws[eemm_cell].value}'
                # net_cell = f'{source_net_col}{i}'  # 网络费
                # net_value = f'¥{source_ws[net_cell].value}'
                # net_value_dj = f'¥{source_ws[net_cell].value}/月'
                # hyg_cell = f'{source_hyg_col}{i}'  # 卫生费
                # hyg_value = f'¥{source_ws[hyg_cell].value}'
                # 创建一个DataFrame包含标题和数据
                data = {
                    '项目': ['水费', '电费', '卫生费', '网络费'],
                    '上月': [swfy_value, seey_value, '', ''],
                    '本月': [bwfy_value, beey_value, '', ''],
                    '实用': [rwfy_value, reey_value, '', ''],
                    '单价': ['¥6/吨', '¥1.2/度', '', ''],
                    '金额': [wtmm_value, eemm_value, '', ''],
                    '备注': ['', '', '', '']
                }

                df = pd.DataFrame(data)

                # 写入DataFrame到Excel
                df.to_excel(writer, sheet_name='收据', index=False, startrow=4 + (i - 2) * 10, header=False)

                # 获取XlsxWriter的Workbook和Worksheet对象
                workbook = writer.book
                worksheet = writer.sheets['收据']

                # 设置标题
                title_col1 = 'A'
                title_cell1 = f'{title_col1}{1 + (i - 2) * 10}'
                title_col2 = 'G'
                title_cell2 = f'{title_col2}{1 + (i - 2) * 10}'
                worksheet.merge_range(f'{title_cell1}:{title_cell2}', '水、电费(专用)收据',
                                      workbook.add_format({'bold': True, 'align': 'center', 'font_size': 14}))

                # 设置用户名称和日期
                yhm_cell = f'{source_ymh_col}{i}'
                yhm_value = source_ws[yhm_cell].value
                yhmc_col = 'A'
                yhmc_cell = f'{yhmc_col}{2 + (i - 2) * 10}'
                yhm_col = 'B'
                yhm_cell = f'{yhm_col}{2 + (i - 2) * 10}'
                worksheet.write(yhmc_cell, '用户名称:', workbook.add_format({'font_size': 12}))
                worksheet.write(yhm_cell, yhm_value, workbook.add_format({'font_size': 12, 'align': 'left'}))

                # datatime_cell = datetime.now().strftime('%Y-%m-%d')
                rq_col = 'F'
                rq_cell = f'{rq_col}{2 + (i - 2) * 10}'
                data_col = 'G'
                data_cell = f'{data_col}{2 + (i - 2) * 10}'
                worksheet.write(rq_cell, '日期:', workbook.add_format({'font_size': 12, 'align': 'right'}))
                worksheet.write(data_cell, datatime_cell, workbook.add_format({'font_size': 12, 'align': 'left'}))
                # 写入用户名和日期

                # 设置标题行格式
                bt_col = 'A'
                bt_cell = f'{bt_col}{4 + (i - 2) * 10}'
                header_format = workbook.add_format({'bold': True, 'bg_color': '#FFFF00', 'align': 'center', 'border': 1})
                worksheet.write_row(bt_cell, ['项目', '上月', '本月', '实用', '单价', '金额', '备注'], header_format)

                # 设置合计金额
                heji_col = 'E'
                heji_cell = f'{heji_col}{9 + (i - 2) * 10}'
                totel_col = 'F'
                totel_cell = f'{totel_col}{9 + (i - 2) * 10}'
                source_totel_cell = f'{source_totel_col}{i}'
                totel_value = f'¥{source_ws[source_totel_cell].value}'
                worksheet.write(heji_cell, '合计:', workbook.add_format({'align': 'right'}))
                worksheet.write(totel_cell, totel_value, workbook.add_format({'align': 'left'}))

            # 设置列宽
            worksheet.set_column('A:A', 10)
            worksheet.set_column('B:G', 15)
        messagebox.showinfo("成功", f"发票文件已保存")
    except Exception as e:
        messagebox.showerror("错误", str(e))

# 创建主窗口
root = tk.Tk()
root.title("水电费管理信息系统")
root.geometry("400x280")

# 添加介绍
intro_text = (
    "欢迎使用水电费发票信息生成系统!\n\n"
    "发票文件保存于程序目录文件夹\n\n"
    "请使用下方的按钮进行操作"
)
intro_label = tk.Label(root, text=intro_text, justify="left")
intro_label.pack(pady=15)

# 添加按钮
upload_button = tk.Button(root, text="上传模板文件  并保存数据", command=upload_file)
upload_button.pack(pady=15)

invoice_button = tk.Button(root, text="使用数据文件  生成发票", command=creat_fap)
invoice_button.pack(pady=15)

# 运行主循环
root.mainloop()

三、具体思路

发现目前二手创业房东越来越多

希望能够帮助大家更方便计算水电费,开发票收据

减少时间成本,给租户更好的房源!!!很重要!!!

看了代码后续交流,嘿嘿嘿!!!

计科专业大学生写的文章支持一下!!!

留下你的痕迹好吗!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值