鱼C论坛

 找回密码
 立即注册
查看: 176|回复: 11

工作簿单元格格式转换求教~~

[复制链接]
发表于 2024-3-19 18:58:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
现有需求如下: (要求PySide6)

1、根据用户指定的工作簿后缀(xls或者xlsx), 用不同的命令打开此工作簿;

2、读取所指定工作簿的所有sheet名,用下拉框让用户指定sheet;

3、读取所指定sheet的所有列名称(可能不一定是第一行,因为有时第一行是工作簿的名称,这个需要怎么处理我还没想好),用下拉框让用户指定要转换格式的列名称;

4、在此sheet中增加一列,命名为“转换后列”;

5、对比用户所指定的列的单元格格式,用下拉框让用户指定转换后的单元格格式(自动屏蔽掉所指定列的本身格式);

6、如果转换成功,把转换后的数据写入“转换后列”中;

7、询问用户是否继续转换,否则退出。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-3-19 18:58:48 | 显示全部楼层
这个任务可以分为几个步骤来实现。首先,我们需要使用`pandas`库来读取Excel文件,用`openpyxl`库来处理Excel文件的格式转换,最后使用`PySide6`库创建图形界面。

下面是一个实现上述需求的示例代码:

  1. import pandas as pd
  2. from openpyxl import load_workbook
  3. from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QMessageBox, QPushButton

  4. class MainWindow(QMainWindow):
  5.     def __init__(self):
  6.         super().__init__()
  7.         self.setWindowTitle("工作簿格式转换")
  8.         self.setGeometry(100, 100, 400, 300)

  9.         self.file_combo = QComboBox(self)
  10.         self.file_combo.setGeometry(50, 50, 300, 30)

  11.         self.sheet_combo = QComboBox(self)
  12.         self.sheet_combo.setGeometry(50, 100, 300, 30)

  13.         self.column_combo = QComboBox(self)
  14.         self.column_combo.setGeometry(50, 150, 300, 30)

  15.         self.format_combo = QComboBox(self)
  16.         self.format_combo.setGeometry(50, 200, 300, 30)

  17.         self.convert_button = QPushButton("转换", self)
  18.         self.convert_button.setGeometry(150, 250, 100, 30)
  19.         self.convert_button.clicked.connect(self.convert)

  20.         self.load_files()
  21.         self.file_combo.currentIndexChanged.connect(self.load_sheets)
  22.         self.sheet_combo.currentIndexChanged.connect(self.load_columns)

  23.     def load_files(self):
  24.         self.file_combo.clear()
  25.         # 在这里根据用户输入的文件后缀来加载文件
  26.         # 这里只是示例,假设用户输入的后缀为".xls"
  27.         filenames = ["file1.xls", "file2.xls", "file3.xls"]
  28.         self.file_combo.addItems(filenames)

  29.     def load_sheets(self):
  30.         self.sheet_combo.clear()
  31.         # 在这里读取用户指定文件的所有sheet名
  32.         filename = self.file_combo.currentText()
  33.         sheets = pd.read_excel(filename, sheet_name=None).keys()
  34.         self.sheet_combo.addItems(sheets)

  35.     def load_columns(self):
  36.         self.column_combo.clear()
  37.         # 在这里读取用户指定sheet的所有列名称
  38.         filename = self.file_combo.currentText()
  39.         sheetname = self.sheet_combo.currentText()
  40.         df = pd.read_excel(filename, sheet_name=sheetname)
  41.         columns = df.columns.tolist()
  42.         self.column_combo.addItems(columns)

  43.     def convert(self):
  44.         # 获取用户选择的转换后的单元格格式
  45.         format_str = self.format_combo.currentText()

  46.         # 在这里进行格式转换并写入到转换后列中
  47.         filename = self.file_combo.currentText()
  48.         sheetname = self.sheet_combo.currentText()
  49.         column_name = self.column_combo.currentText()

  50.         df = pd.read_excel(filename, sheet_name=sheetname)

  51.         # 进行单元格格式转换,假设将所有数据转换为文本格式
  52.         df["转换后列"] = df[column_name].astype(str)

  53.         # 使用openpyxl库来保存格式转换后的数据
  54.         with pd.ExcelWriter(filename, engine="openpyxl") as writer:
  55.             writer.book = load_workbook(filename)
  56.             df.to_excel(writer, sheet_name=sheetname, index=False)

  57.         QMessageBox.information(self, "转换成功", "格式转换成功!")

  58. if __name__ == "__main__":
  59.     app = QApplication([])
  60.     window = MainWindow()
  61.     window.show()
  62.     app.exec()
复制代码


请注意,这只是一个示例代码,你需要根据自己的实际情况进行修改和完善。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-19 19:11:56 | 显示全部楼层
FishC 发表于 2024-3-19 18:58
这个任务可以分为几个步骤来实现。首先,我们需要使用`pandas`库来读取Excel文件,用`openpyxl`库来处理Exc ...

这报错是什么意思?
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\Excel_Change.py", line 1, in <module>
    import pandas as pd
  File "D:\Python\pythonProject\.venv\Lib\site-packages\pandas\__init__.py", line 29, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy: Error importing numpy: you should not try to import numpy from
        its source directory; please exit the numpy source tree, and relaunch
        your python interpreter from there.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-19 19:12:13 | 显示全部楼层
凊风 发表于 2024-03-19 19:11
这报错是什么意思?
Traceback (most recent call la ...


这个错误通常是由于在使用`pandas`库之前,在导入`numpy`库时发生了问题。根据错误信息,它建议您不要从numpy的源代码目录中导入numpy,而是应该退出numpy源代码目录并从那里重新启动Python解释器。

解决此问题的方法是确保您的Python环境中已正确安装了`numpy`库,最好是通过`pip`命令进行安装。然后,检查您的Python代码文件中是否存在与numpy相关的任何import语句,并确保它们没有任何问题。

如果上述步骤仍然无法解决问题,您可以尝试以下几种方法:
1. 重启您的Python解释器。
2. 如果您使用的是Jupyter Notebook等类似的开发环境,请尝试关闭并重新启动该环境。
3. 检查您的Python环境是否有多个版本,确保您正在使用所需的版本。

希望这些提示能帮助您解决问题!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-19 19:20:45 | 显示全部楼层
FishC 发表于 2024-3-19 19:12
这个错误通常是由于在使用`pandas`库之前,在导入`numpy`库时发生了问题。根据错误信息,它建议您不要 ...

import pandas as pd
from openpyxl import load_workbook
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QMessageBox, QPushButton


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("工作簿格式转换")
        self.setGeometry(100, 100, 400, 300)

        self.file_combo = QComboBox(self)
        self.file_combo.setGeometry(50, 50, 300, 30)

        self.sheet_combo = QComboBox(self)
        self.sheet_combo.setGeometry(50, 100, 300, 30)

        self.column_combo = QComboBox(self)
        self.column_combo.setGeometry(50, 150, 300, 30)

        self.format_combo = QComboBox(self)
        self.format_combo.setGeometry(50, 200, 300, 30)

        self.convert_button = QPushButton("转换", self)
        self.convert_button.setGeometry(150, 250, 100, 30)
        self.convert_button.clicked.connect(self.convert)

        self.load_files()
        self.file_combo.currentIndexChanged.connect(self.load_sheets)
        self.sheet_combo.currentIndexChanged.connect(self.load_columns)

    def load_files(self):
        self.file_combo.clear()
        # 在这里根据用户输入的文件后缀来加载文件
        # 这里只是示例,假设用户输入的后缀为".xls"
        filenames = ["file1.xls", "file2.xls", "file3.xls"]
        self.file_combo.addItems(filenames)

    def load_sheets(self):
        self.sheet_combo.clear()
        # 在这里读取用户指定文件的所有sheet名
        filename = self.file_combo.currentText()
        sheets = pd.read_excel(filename, sheet_name=None).keys()
        self.sheet_combo.addItems(sheets)

    def load_columns(self):
        self.column_combo.clear()
        # 在这里读取用户指定sheet的所有列名称
        filename = self.file_combo.currentText()
        sheetname = self.sheet_combo.currentText()
        df = pd.read_excel(filename, sheet_name=sheetname)
        columns = df.columns.tolist()
        self.column_combo.addItems(columns)

    def convert(self):
        # 获取用户选择的转换后的单元格格式
        format_str = self.format_combo.currentText()

        # 在这里进行格式转换并写入到转换后列中
        filename = self.file_combo.currentText()
        sheetname = self.sheet_combo.currentText()
        column_name = self.column_combo.currentText()

        df = pd.read_excel(filename, sheet_name=sheetname)

        # 进行单元格格式转换,假设将所有数据转换为文本格式
        df["转换后列"] = df[column_name].astype(str)

        # 使用openpyxl库来保存格式转换后的数据
        with pd.ExcelWriter(filename, engine="openpyxl") as writer:
            writer.book = load_workbook(filename)
            df.to_excel(writer, sheet_name=sheetname, index=False)

        QMessageBox.information(self, "转换成功", "格式转换成功!")


if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

这段代码报错:

Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\Excel_Change.py", line 1, in <module>
    import pandas as pd
  File "D:\Python\pythonProject\.venv\Lib\site-packages\pandas\__init__.py", line 29, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy: Error importing numpy: you should not try to import numpy from
        its source directory; please exit the numpy source tree, and relaunch
        your python interpreter from there.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-19 19:21:00 | 显示全部楼层
凊风 发表于 2024-03-19 19:20
import pandas as pd
from openpyxl import load_wor ...


根据报错信息,这个错误与导入`numpy`库有关。您可以尝试以下几种解决方法:

1. 确保您已正确安装了`numpy`库。您可以使用命令`pip install numpy`来安装或更新`numpy`库。

2. 如果您已经安装了`numpy`库但仍然出现此错误,可能是由于您的Python环境中存在多个版本的`numpy`库导致冲突。您可以尝试卸载所有版本的`numpy`库,然后重新安装最新版本的`numpy`库。

3. 如果您正在使用虚拟环境,请确保您的虚拟环境中已正确安装了`numpy`库。您可以激活虚拟环境并再次尝试运行代码。

4. 检查您的Python环境中是否有其他模块或库与`numpy`库发生冲突,并尝试禁用或卸载这些冲突的模块或库。

如果上述方法仍不能解决问题,请尝试重新启动您的Python解释器或重启您的开发环境(如Jupyter Notebook)。希望这些解决方案能够帮助您解决问题!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-19 19:22:41 | 显示全部楼层
FishC 发表于 2024-3-19 19:21
根据报错信息,这个错误与导入`numpy`库有关。您可以尝试以下几种解决方法:

1. 确保您已正确安装了 ...

关键是这段代码并没有引用numpy啊。。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-19 19:22:57 | 显示全部楼层
凊风 发表于 2024-03-19 19:22
关键是这段代码并没有引用numpy啊。。。。


非常抱歉,我之前的回答有误。根据您提供的代码,您需要确保已正确安装了`pandas`和`openpyxl`两个库。如果您已经安装了这两个库,但仍然出现报错,可能是由于您的Python环境配置有问题。

请尝试以下解决方法:

1. 确保您使用的是最新版本的`pandas`和`openpyxl`库。您可以使用以下命令升级这两个库:
  
  1. pip install --upgrade pandas openpyxl
复制代码


2. 检查您的Python环境配置。建议使用Anaconda或Miniconda等发行版来创建一个干净的环境,并在该环境中安装所需的依赖项。

3. 如果您使用的是Jupyter Notebook等集成开发环境,请重启内核并重新运行代码,以确保所有库都正确加载。

如果上述方法仍无法解决问题,请提供完整的错误信息,以便排查问题所在。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-19 19:23:47 | 显示全部楼层
FishC 发表于 2024-3-19 19:22
非常抱歉,我之前的回答有误。根据您提供的代码,您需要确保已正确安装了`pandas`和`openpyxl`两个库。 ...

`pandas`和`openpyxl`库也没有问题。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-19 19:24:21 | 显示全部楼层
凊风 发表于 2024-03-19 19:23
`pandas`和`openpyxl`库也没有问题。。。


非常抱歉给您带来困扰。我注意到我之前的回答中确实有误。实际上,在这段代码中,您不需要引入`numpy`库。将以下示例代码替换为您的代码即可:

  1. import pandas as pd
  2. from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QMessageBox, QPushButton

  3. class MainWindow(QMainWindow):
  4.     def __init__(self):
  5.         super().__init__()

  6.         self.setWindowTitle("工作簿格式转换")
  7.         self.setGeometry(100, 100, 400, 300)

  8.         self.file_combo = QComboBox(self)
  9.         self.file_combo.setGeometry(50, 50, 300, 30)

  10.         self.sheet_combo = QComboBox(self)
  11.         self.sheet_combo.setGeometry(50, 100, 300, 30)

  12.         self.column_combo = QComboBox(self)
  13.         self.column_combo.setGeometry(50, 150, 300, 30)

  14.         self.format_combo = QComboBox(self)
  15.         self.format_combo.setGeometry(50, 200, 300, 30)

  16.         self.convert_button = QPushButton("转换", self)
  17.         self.convert_button.setGeometry(150, 250, 100, 30)
  18.         self.convert_button.clicked.connect(self.convert)

  19.         self.load_files()
  20.         self.file_combo.currentIndexChanged.connect(self.load_sheets)
  21.         self.sheet_combo.currentIndexChanged.connect(self.load_columns)

  22.     def load_files(self):
  23.         self.file_combo.clear()
  24.         # 在这里根据用户输入的文件后缀来加载文件
  25.         filenames = # 根据用户输入的工作簿后缀加载文件并获取文件名列表
  26.         self.file_combo.addItems(filenames)

  27.     def load_sheets(self):
  28.         self.sheet_combo.clear()
  29.         # 在这里读取用户指定文件的所有sheet名
  30.         filename = self.file_combo.currentText()
  31.         sheets = pd.read_excel(filename, sheet_name=None).keys()
  32.         self.sheet_combo.addItems(sheets)

  33.     def load_columns(self):
  34.         self.column_combo.clear()
  35.         # 在这里读取用户指定sheet的所有列名称
  36.         filename = self.file_combo.currentText()
  37.         sheetname = self.sheet_combo.currentText()
  38.         df = pd.read_excel(filename, sheet_name=sheetname)
  39.         columns = df.columns.tolist()
  40.         self.column_combo.addItems(columns)

  41.     def convert(self):
  42.         # 获取用户选择的转换后的单元格格式
  43.         format_str = self.format_combo.currentText()

  44.         # 在这里进行格式转换并写入到转换后的列中
  45.         filename = self.file_combo.currentText()
  46.         sheetname = self.sheet_combo.currentText()
  47.         column_name = self.column_combo.currentText()

  48.         # 进行格式转换操作,并将结果写入"转换后列"
  49.         df = pd.read_excel(filename, sheet_name=sheetname)
  50.         # 假设我们将选定的列的每个单元格都转换为指定的格式,这里使用"文本"作为示例
  51.         df["转换后列"] = df[column_name].astype(str)

  52.         # 使用openpyxl保存转换后的结果
  53.         with pd.ExcelWriter(filename, engine="openpyxl") as writer:
  54.             writer.book = load_workbook(filename)
  55.             df.to_excel(writer, sheet_name=sheetname, index=False)

  56.         QMessageBox.information(self, "转换成功", "格式转换成功!")

  57. if __name__ == "__main__":
  58.     app = QApplication()
  59.     window = MainWindow()
  60.     window.show()
  61.     app.exec()
复制代码


再次向您致以由衷的歉意,并感谢您的耐心。如果还有任何疑问,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-19 19:27:17 | 显示全部楼层
FishC 发表于 2024-3-19 19:24
非常抱歉给您带来困扰。我注意到我之前的回答中确实有误。实际上,在这段代码中,您不需要引入`numpy` ...

def load_files(self):
        self.file_combo.clear()
        # 在这里根据用户输入的文件后缀来加载文件
        filenames = # 根据用户输入的工作簿后缀加载文件并获取文件名列表
        self.file_combo.addItems(filenames)
工作簿要由用户来指定,再根据所指定的后缀(xls或者xlsx)打开工作簿
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-19 19:27:50 | 显示全部楼层
凊风 发表于 2024-03-19 19:27
def load_files(self):
        self.file_combo.cle ...


非常抱歉之前的回答没有完全理解您的需求。根据您的需求,我们需要在用户选择工作簿后缀后,打开对应的工作簿文件。请使用以下代码来实现该功能:

  1. import pandas as pd
  2. from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QMessageBox, QPushButton, QFileDialog

  3. class MainWindow(QMainWindow):
  4.     def __init__(self):
  5.         super().__init__()
  6.         self.setWindowTitle("工作簿格式转换")
  7.         self.setGeometry(100, 100, 400, 300)
  8.         
  9.         self.file_combo = QComboBox(self)
  10.         self.file_combo.setGeometry(50, 50, 300, 30)
  11.         
  12.         self.sheet_combo = QComboBox(self)
  13.         self.sheet_combo.setGeometry(50, 100, 300, 30)
  14.         
  15.         self.column_combo = QComboBox(self)
  16.         self.column_combo.setGeometry(50, 150, 300, 30)
  17.         
  18.         self.format_combo = QComboBox(self)
  19.         self.format_combo.setGeometry(50, 200, 300, 30)
  20.         
  21.         self.convert_button = QPushButton("转换", self)
  22.         self.convert_button.setGeometry(150, 250, 100, 30)
  23.         self.convert_button.clicked.connect(self.convert)
  24.         
  25.         self.load_files()
  26.         self.file_combo.currentIndexChanged.connect(self.load_sheets)
  27.         self.sheet_combo.currentIndexChanged.connect(self.load_columns)

  28.     def load_files(self):
  29.         self.file_combo.clear()
  30.         # 使用QFileDialog让用户选择要打开的工作簿文件
  31.         options = QFileDialog.Options()
  32.         options |= QFileDialog.ReadOnly
  33.         file, _ = QFileDialog.getOpenFileName(self, "选择工作簿文件", "", "Excel Files (*.xls *.xlsx)", options=options)
  34.         if file:
  35.             self.file_combo.addItem(file)

  36.     def load_sheets(self):
  37.         self.sheet_combo.clear()
  38.         # 在这里读取用户指定文件的所有sheet名
  39.         filename = self.file_combo.currentText()
  40.         sheets = pd.read_excel(filename, sheet_name=None).keys()
  41.         self.sheet_combo.addItems(sheets)

  42.     def load_columns(self):
  43.         self.column_combo.clear()
  44.         # 在这里读取用户指定sheet的所有列名称
  45.         filename = self.file_combo.currentText()
  46.         sheetname = self.sheet_combo.currentText()
  47.         df = pd.read_excel(filename, sheet_name=sheetname)
  48.         columns = df.columns.tolist()
  49.         self.column_combo.addItems(columns)

  50.     def convert(self):
  51.         # 获取用户选择的转换后的单元格格式
  52.         format_str = self.format_combo.currentText()
  53.         # 在这里进行格式转换并写入到转换后的列中
  54.         filename = self.file_combo.currentText()
  55.         sheetname = self.sheet_combo.currentText()
  56.         column_name = self.column_combo.currentText()
  57.         
  58.         # 进行格式转换操作,并将结果写入"转换后列"
  59.         df = pd.read_excel(filename, sheet_name=sheetname)
  60.         # 假设我们将选定的列的每个单元格都转换为指定的格式,这里使用"文本"作为示例
  61.         df = df.astype(str)
  62.         
  63.         with pd.ExcelWriter(filename, engine="openpyxl") as writer:
  64.             writer.book = load_workbook(filename)
  65.             df.to_excel(writer, sheet_name=sheetname, index=False)
  66.         
  67.         QMessageBox.information(self, "转换成功", "格式转换成功!")


  68. if __name__ == "__main__":
  69.     app = QApplication([])
  70.     window = MainWindow()
  71.     window.show()
  72.     app.exec()
复制代码


这样,用户将能够通过对话框选择所需的工作簿文件,并根据后缀自动打开相应的文件。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 01:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表