鱼C论坛

 找回密码
 立即注册
查看: 461|回复: 1

[已解决]将txt导入到excel

[复制链接]
发表于 2024-9-29 15:30:20 | 显示全部楼层 |阅读模式

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

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

x
需要将一个txt文件导入到excel文件,要求如下:
需要做一个图形界面,用于指定需要转换的txt文件,并且指定生成的excel的放置文件夹,excel命名为“转换后excel.xlsx”


txt文件内容如下,列出两行作为说明
CA-03-15-A1B-N            S1    BW    φ60.3*4.0,S30408-
CA-03-15-A1B-N            S2    BW    φ60.3*4.0,S30408-

需要导入到excel,对excel第一行指定文本内容,从第二行填写txt的内容,如下
管线号        焊缝编号        焊接类型        主要信息
CA-03-15-A1B-N        S1        BW                蠁60.3*4.0,S30408-
CA-03-15-A1B-N        S2        BW                 蠁60.3*4.0,S30408-

求助各路大神,主要有点懒,都不想慢慢写了。
最佳答案
2024-9-29 15:30:31
你可以使用Python来实现这个任务。我们将使用`tkinter`库创建图形界面,让用户选择txt文件和输出文件夹,同时用`pandas`库处理文件转换并保存为Excel文件。以下是详细的代码步骤:

1. 安装需要的库:
   
  1. pip install pandas openpyxl
复制代码


2. 编写代码:

  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox
  3. import pandas as pd

  4. def load_txt():
  5.     txt_file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
  6.     if txt_file_path:
  7.         txt_entry.delete(0, tk.END)
  8.         txt_entry.insert(0, txt_file_path)

  9. def save_excel():
  10.     output_folder_path = filedialog.askdirectory()
  11.     if output_folder_path:
  12.         output_entry.delete(0, tk.END)
  13.         output_entry.insert(0, output_folder_path)

  14. def convert():
  15.     txt_file_path = txt_entry.get()
  16.     output_folder_path = output_entry.get()
  17.    
  18.     if not txt_file_path or not output_folder_path:
  19.         messagebox.showerror("Error", "Please select both the input file and the output folder.")
  20.         return
  21.    
  22.     # 读取txt文件内容
  23.     try:
  24.         with open(txt_file_path, 'r', encoding='utf-8') as f:
  25.             data = f.readlines()
  26.         
  27.         # 预处理txt内容
  28.         rows = []
  29.         for line in data:
  30.             parts = line.strip().split()
  31.             if len(parts) >= 4:
  32.                 # 按照给定格式将信息进行拼接
  33.                 row = [parts[0], parts[1], parts[2], ' '.join(parts[3:]).replace('φ', '')]
  34.                 rows.append(row)
  35.         
  36.         # 创建DataFrame并保存为Excel
  37.         df = pd.DataFrame(rows, columns=['管线号', '焊缝编号', '焊接类型', '主要信息'])
  38.         output_path = f"{output_folder_path}/转换后excel.xlsx"
  39.         df.to_excel(output_path, index=False)
  40.         messagebox.showinfo("Success", f"Excel file has been saved to {output_path}")
  41.    
  42.     except Exception as e:
  43.         messagebox.showerror("Error", str(e))

  44. # 创建图形界面
  45. root = tk.Tk()
  46. root.title("Txt to Excel Converter")

  47. # 输入txt文件路径
  48. tk.Label(root, text="选择Txt文件:").grid(row=0, column=0, padx=10, pady=10, sticky='w')
  49. txt_entry = tk.Entry(root, width=50)
  50. txt_entry.grid(row=0, column=1, padx=10, pady=10)
  51. tk.Button(root, text="浏览...", command=load_txt).grid(row=0, column=2, padx=10, pady=10)

  52. # 输出Excel文件夹路径
  53. tk.Label(root, text="选择输出文件夹:").grid(row=1, column=0, padx=10, pady=10, sticky='w')
  54. output_entry = tk.Entry(root, width=50)
  55. output_entry.grid(row=1, column=1, padx=10, pady=10)
  56. tk.Button(root, text="浏览...", command=save_excel).grid(row=1, column=2, padx=10, pady=10)

  57. # 转换按钮
  58. tk.Button(root, text="转换", command=convert).grid(row=2, column=1, padx=10, pady=20)

  59. root.mainloop()
复制代码


通过以上代码,你可以创建一个简单的图形界面,实现txt文件到excel文件的转换。这个步骤能帮助你完成你的需求。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

原始数据.txt

3.51 KB, 下载次数: 0

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-9-29 15:30:31 | 显示全部楼层    本楼为最佳答案   
你可以使用Python来实现这个任务。我们将使用`tkinter`库创建图形界面,让用户选择txt文件和输出文件夹,同时用`pandas`库处理文件转换并保存为Excel文件。以下是详细的代码步骤:

1. 安装需要的库:
   
  1. pip install pandas openpyxl
复制代码


2. 编写代码:

  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox
  3. import pandas as pd

  4. def load_txt():
  5.     txt_file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
  6.     if txt_file_path:
  7.         txt_entry.delete(0, tk.END)
  8.         txt_entry.insert(0, txt_file_path)

  9. def save_excel():
  10.     output_folder_path = filedialog.askdirectory()
  11.     if output_folder_path:
  12.         output_entry.delete(0, tk.END)
  13.         output_entry.insert(0, output_folder_path)

  14. def convert():
  15.     txt_file_path = txt_entry.get()
  16.     output_folder_path = output_entry.get()
  17.    
  18.     if not txt_file_path or not output_folder_path:
  19.         messagebox.showerror("Error", "Please select both the input file and the output folder.")
  20.         return
  21.    
  22.     # 读取txt文件内容
  23.     try:
  24.         with open(txt_file_path, 'r', encoding='utf-8') as f:
  25.             data = f.readlines()
  26.         
  27.         # 预处理txt内容
  28.         rows = []
  29.         for line in data:
  30.             parts = line.strip().split()
  31.             if len(parts) >= 4:
  32.                 # 按照给定格式将信息进行拼接
  33.                 row = [parts[0], parts[1], parts[2], ' '.join(parts[3:]).replace('φ', '')]
  34.                 rows.append(row)
  35.         
  36.         # 创建DataFrame并保存为Excel
  37.         df = pd.DataFrame(rows, columns=['管线号', '焊缝编号', '焊接类型', '主要信息'])
  38.         output_path = f"{output_folder_path}/转换后excel.xlsx"
  39.         df.to_excel(output_path, index=False)
  40.         messagebox.showinfo("Success", f"Excel file has been saved to {output_path}")
  41.    
  42.     except Exception as e:
  43.         messagebox.showerror("Error", str(e))

  44. # 创建图形界面
  45. root = tk.Tk()
  46. root.title("Txt to Excel Converter")

  47. # 输入txt文件路径
  48. tk.Label(root, text="选择Txt文件:").grid(row=0, column=0, padx=10, pady=10, sticky='w')
  49. txt_entry = tk.Entry(root, width=50)
  50. txt_entry.grid(row=0, column=1, padx=10, pady=10)
  51. tk.Button(root, text="浏览...", command=load_txt).grid(row=0, column=2, padx=10, pady=10)

  52. # 输出Excel文件夹路径
  53. tk.Label(root, text="选择输出文件夹:").grid(row=1, column=0, padx=10, pady=10, sticky='w')
  54. output_entry = tk.Entry(root, width=50)
  55. output_entry.grid(row=1, column=1, padx=10, pady=10)
  56. tk.Button(root, text="浏览...", command=save_excel).grid(row=1, column=2, padx=10, pady=10)

  57. # 转换按钮
  58. tk.Button(root, text="转换", command=convert).grid(row=2, column=1, padx=10, pady=20)

  59. root.mainloop()
复制代码


通过以上代码,你可以创建一个简单的图形界面,实现txt文件到excel文件的转换。这个步骤能帮助你完成你的需求。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-22 01:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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