批量填充excel单元格,生成不同的excel文件

源码分享:

import os
import time
import sys
import subprocess
import xlwings as xw
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon, QPalette, QBrush, QPixmap
from PyQt5.QtCore import pyqtSignal, QTimer, QSize, QStorageInfo
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import Qt
from openpyxl import load_workbook
from os.path import abspath
from PyQt5.QtWidgets import QCheckBox
class MainWindow(QWidget):
    signal1 = pyqtSignal(str)

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        # # 窗体标题和尺寸
        self.resize(1200,600)
        self.font = QtGui.QFont()
        self.font.setFamily("微软雅黑")  # 括号里可以设置成自己想要的其它字体
        self.font.setPointSize(12)  # 括号里的数字可以设置成自己想要的字体大小
        self.setFont(self.font)
        self.setWindowTitle('word与excel数据批量填充')
        layout = QVBoxLayout()
        self.layout = layout

        self.layout211 = QVBoxLayout()
        self.layout.addLayout(self.layout211)
        self.layout21 = QHBoxLayout()
        self.layout211.addLayout(self.layout21)
        self.layout_2 = QHBoxLayout()
        self.layout21.addLayout(self.layout_2)
        self.layout_2_1 = QHBoxLayout()
        self.layout21.addLayout(self.layout_2_1)

        self.layout31 = QHBoxLayout()
        self.layout211.addLayout(self.layout31)
        self.layout_31 = QHBoxLayout()
        self.layout31.addLayout(self.layout_31)
        self.layout_32 = QHBoxLayout()
        self.layout31.addLayout(self.layout_32)


        self.header_layout = QHBoxLayout()
        self.layout_4 = QVBoxLayout()
        self.layout.addLayout(self.layout_4)
        self.middle_layout = QHBoxLayout()

        self.layout_3 = QHBoxLayout()
        self.layout.addLayout(self.layout_3)
        self.footer_layout = QHBoxLayout()

        self.init_header()
        self.init_header2()
        self.init_middle()
        self.init_footer()

        #给窗体设置元素的排列方式
        self.setLayout(layout)  #设置整体的布局
        #参数设置
        self.path1 = None
        self.path2 = None
        self.number = 0
        # self.signal_test2.connect (self.test2)
        # self.signal_test3.connect (self.test3)
        # self.signal_test4.connect (self.test4)
        self.str1 = None
        self.str2 = None
        self.data_cols = []

    def init_header(self):
        # 创建按钮
        self.btn_choice_file = QPushButton('选择模版文件')
        self.btn_choice_file.clicked.connect(self.choose_file)
        self.header_layout.addWidget(self.btn_choice_file)
        self.layout_2.addLayout(self.header_layout)
        self.layout_2.addSpacing(50)
        #标签
        header_layout2 = QHBoxLayout()
        self.label = QLabel()
        self.label.setText('路径:')
        header_layout2.addWidget(self.label)
        # 输入框
        txt_asin = QLineEdit()
        self.txt_asin = txt_asin
        self.txt_asin.setReadOnly(True)
        header_layout2.addWidget(txt_asin)
        self.layout_2_1.addLayout(header_layout2)
        return self.header_layout

    def init_header2(self):
        # 创建按钮
        self.btn_choice_file2 = QPushButton('选填充数据')
        self.btn_choice_file2.clicked.connect(self.choose_file2)
        self.header_layout12 = QHBoxLayout()
        self.header_layout12.addWidget(self.btn_choice_file2)
        self.layout_31.addLayout(self.header_layout12)
        self.layout_31.addSpacing(50)
        # 标签
        header_layout2 = QHBoxLayout()
        self.label = QLabel()
        self.label.setText('路径:')
        header_layout2.addWidget(self.label)
        # 输入框
        txt_asin2 = QLineEdit()
        self.txt_asin2 = txt_asin2
        self.txt_asin2.setReadOnly(True)
        header_layout2.addWidget(txt_asin2)
        self.layout_32.addLayout(header_layout2)
        return self.header_layout

    def init_middle(self):
        # 文本框
        self.table_widget = QTableWidget(self)
        self.table_widget.setFont (self.font)
        self.middle_layout.addWidget(self.table_widget)
        self.layout_4.addLayout(self.middle_layout)
        return self.middle_layout

    def init_footer(self):

        #  开始按钮
        btn_1 = QPushButton('开始')
        btn_1.clicked.connect(self.start)
        self.layout_3.addWidget(btn_1)
        self.layout_3.addStretch()
        btn_2 = QPushButton('结束')
        self.layout_3.addWidget(btn_2)
        return self.footer_layout

    def choose_file(self):
        filename,_ = QFileDialog.getOpenFileName(self, "选择文件", "/", "All Files (*)")
        self.path1 = filename
        self.txt_asin.setText(self.path1)

    def choose_file2(self):
        filename, _ = QFileDialog.getOpenFileName(self, "选择文件2", "/", "All Files (*)")
        self.path2 = filename
        self.txt_asin2.setText(self.path2)
        self.fill_date()

    def fill_date(self):
        print(23422)
        wb = load_workbook (abspath (self.path2))
        wb.active
        sh = wb['Sheet1']
        max_row = sh.max_row
        self.col = max_col = sh.max_column
        self.table_widget.setColumnCount(sh.max_column+1)
        self.table_widget.setRowCount(sh.max_row)
        #隐藏列表头
        self.table_widget.verticalHeader().setVisible(False)
        # #隐藏行表头
        self.table_widget.horizontalHeader( ).setVisible (False)
        #QTableWidget设置整行选中
        self.table_widget.setSelectionBehavior (QAbstractItemView.SelectRows);
        self.all_header_combobox = []
        self.selcet_data = []
        self.selcet_data2 = []
        header_field = []
        # 逐行循环读取数据并填充到QTableWidget
        for row in range (1, max_row + 1):
            # 插入单选框
            checkBox = QCheckBox ( )
            if row==1:
                checkBox.setText('全选')
            self.table_widget.setCellWidget (row-1, 0, checkBox)
            checkBox.stateChanged.connect(self.on_state_changed)
            self.all_header_combobox.append(checkBox)
            print (f"读取第一行数据:{row}")

            for col in range (0, max_col):
                row_value = sh[row][col].value
                if row ==1:
                    self.data_cols.append(row_value)
                self.table_widget.setItem(row-1, col+1, QTableWidgetItem(str(row_value)))
        self.table_widget.horizontalHeader ( ).setSectionResizeMode (QHeaderView.Stretch)
        self.table_widget.horizontalHeader ( ).setSectionResizeMode (0, QHeaderView.Interactive)
        self.table_widget.setColumnWidth (0, 100)  # 设置第0列宽度
        self.all_index = []
        self.index = []
        for k in range(len(self.all_header_combobox)):
            self.all_index.append(k)

    def on_state_changed(self):
        row = self.table_widget.currentRow()
        print(row,'hang')
        try:
            if self.sender().checkState() == Qt.Checked:
                if row == 0:
                    for i in self.all_header_combobox:
                        i.setChecked(True)
                    self.index = self.all_index
                    print(self.index)
                else:
                    self.index.append(row)
                    self.index.sort()
                    self.index = list(set(self.index))
                    print(self.index,'222',self.all_index)
                    if self.index == self.all_index[1::]:
                        self.all_header_combobox[0].setChecked (True)
            else:
                if row == 0:
                    for i in self.all_header_combobox:
                        i.setChecked(False)
                    self.index = []
                    print(self.index,'kong')
                else:
                    self.index = list(set(self.index))
                    try:
                        self.index.remove (row)
                    except:
                         pass
                    if not self.index == self.all_index[1::]:
                        self.all_header_combobox[0].setChecked (False)
                        try:
                            self.index.remove (0)
                        except:
                            pass
                    if self.index ==[]:
                        self.index = []
                        try:
                            self.all_header_combobox[0].setChecked(False)
                            self.index.remove (0)
                        except Exception as e:
                            print(e)
        except Exception as e:
            print(e)

    def start(self):
        print(self.index,self.col)
        self.data2 = []
        for i in self.index:
            data = []
            for j in range(1,self.col-1):
                contents = self.table_widget.item(i, j).text()
                data.append(contents)
            self.data2.append(data)
        print(self.data2)
        self.tihuan()

    def tihuan(self):
        if 0 in self.index:
            self.index.remove(0)
        print(self.index,98985555)
        try:
            subprocess.call ("taskkill /f /im  wps.exe",shell=True)

            subprocess.call ("taskkill /f /im  excel.exe",shell=True)
        except Exception as e:
            print(e)
        try:
            app = xw.App (visible=False, add_book=False)
            for row in self.index:
                wb = app.books.open (self.path1)
                app.display_alerts = False
                app.screen_updating = False
                self.sht = wb.sheets[0]
                a = b = 0
                save_path = None
                for index,v in enumerate(self.data_cols):
                    if index == len(self.data_cols)-2:
                        a = self.table_widget.item (row,index+1).text ( )
                    elif index == len(self.data_cols)-1:
                        b = self.table_widget.item (row,index+1).text ( )
                    else:
                        # 赋值替换
                        self.sht.range(v).value = self.table_widget.item (row,index+1).text ( )
                    if not (a == 0 or b == 0):
                        save_path = os.path.join(a,b)
                if not len(save_path) == 0:
                    print(a,b,999)
                    print(save_path,9999)
                    wb.save(save_path)
            app.quit()
            subprocess.call ("taskkill /f /im  wps.exe",shell=True)
            subprocess.call("taskkill /f /im  excel.exe",shell=True)
        except Exception as e:
            print(e,'111')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()
  • 18
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 要在Excel批量生成二维码9,可以按照以下步骤进行操作: 1. 首先,确保已经安装了可以用于生成二维码的插件或工具,例如二维码生成器。可以在互联网上搜索并下载安装。 2. 打开Excel,并在一个空白单元格中输入第一个需要生成二维码的内容,例如一个链接、文本等。 3. 将这个单元格选中,然后找到插件或工具的功能按钮或选项,选择批量生成二维码的功能。 4. 在批量生成二维码的功能中,设定好生成二维码的数量,这里是9个。 5. 根据插件或工具的操作步骤,选择好二维码生成的样式和尺寸等参数,并确保选择了将二维码添加到Excel的选项。 6. 点击生成按钮或确认按钮,等待插件或工具完成批量生成二维码的操作。 7. 一旦生成完成,就可以在Excel中看到9个二维码按照设定的样式和尺寸添加到了相应的单元格中。 8. 如果需要,可以调整每个二维码所在单元格的大小,以便更好地显示。 通过以上步骤,就可以在Excel批量生成9个二维码了。如果需要生成其他数量的二维码,只需在第三步中设定相应的参数即可。 ### 回答2: 要批量生成二维码9,可以借助Excel的数据处理和宏功能来实现。以下是生成二维码9的步骤: 1. 准备数据:在Excel中创建一个工作表,将需要生成二维码的数据按照一列一行的方式输入到表格中。 2. 导入插件:下载并安装一个二维码生成插件,常用的有QR Code Generator或Zint Barcode Studio等。 3. 批量生成:在Excel中,创建一个宏(Macro),用于循环遍历每个数据,并调用插件生成对应的二维码。宏的代码可以使用VBA(Visual Basic for Applications)来编写,例如: ```vba Sub GenerateQRCode() Dim rng As Range Dim cell As Range Dim barcode As Object Set rng = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row) '定义数据范围 For Each cell In rng Set barcode = CreateObject("BARCODE.BarcodeCtrl.1") '创建插件对象 barcode.Code = cell.Value '设置二维码内容 ' 设置二维码生成参数,例如尺寸、颜色等 barcode.Resolution = 300 barcode.BarcodeType = 0 barcode.BackgroundColor = RGB(255, 255, 255) barcode.ForegroundColor = RGB(0, 0, 0) ' 生成二维码图片,并保存 barcode.SaveImage "路径\生成的二维码\" & cell.Value & ".png" Set barcode = Nothing '释放资源 Next cell End Sub ``` 在代码中,需要根据插件的具体使用方法进行调整,比如设置二维码尺寸、颜色等参数,并指定生成的二维码保存的路径。 4. 运行宏:保存宏并关闭编辑器,回到Excel界面。在工具栏中找到“开发工具”菜单,选择“宏”,然后选择刚才创建的宏(GenerateQRCode),点击运行即可开始批量生成二维码。 以上就是通过Excel批量生成二维码9的方法。注意,使用插件生成二维码需要插件的支持,插件的安装和使用方法可以参考插件的官方文档或使用说明。 ### 回答3: 在Excel批量生成二维码是可行的。首先,需要安装一个二维码生成器插件,如ZXing插件。然后,需要准备一个包含需生成二维码的内容的Excel表格。 在Excel表格中,可以选择一个列作为二维码生成的基础内容。例如,选中A列,将需要生成二维码的内容填充到A1、A2、A3等单元格中。 接下来,在Excel菜单栏选择“插入”-“插入二维码”。选择插入二维码的位置,弹出插入二维码的对话框。在对话框中,选择需要生成二维码的单元格范围,也就是选择A1、A2、A3等单元格。然后,点击确定生成二维码。 生成的二维码将会自动插入到选中的单元格中。插入的二维码会根据单元格的内容自动更新,这样就可以批量生成多个二维码了。 如果需要批量生成大量的二维码,可以使用Excel的自动填充功能。在A1单元格生成好二维码后,选择该单元格,将鼠标移到右下角的小方块上,光标变成十字箭头后,按住鼠标左键向下拖动,Excel会自动填充生成多个二维码。 生成的二维码可以保存为图片,进一步应用到其他文档或打印出来使用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值