-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_to_word_gui.py
More file actions
258 lines (201 loc) · 10.3 KB
/
csv_to_word_gui.py
File metadata and controls
258 lines (201 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
CSV to Word Converter GUI
This script provides a graphical user interface for converting CSV files with
product specifications back to Word documents, preserving the original structure.
"""
import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from threading import Thread
import importlib.util
import traceback
import datetime
class RedirectText:
"""Redirect stdout to a text widget."""
def __init__(self, text_widget):
self.text_widget = text_widget
self.buffer = ""
def write(self, string):
self.buffer += string
self.text_widget.configure(state="normal")
self.text_widget.insert(tk.END, string)
self.text_widget.see(tk.END)
self.text_widget.configure(state="disabled")
def flush(self):
self.buffer = ""
class CSVToWordConverterApp:
"""Main application class for the CSV to Word converter."""
def __init__(self, root):
self.root = root
self.root.title("CSV to Word Converter")
self.root.geometry("800x600")
self.root.minsize(600, 400)
self.input_files = []
self.output_dir = ""
self.setup_ui()
def setup_ui(self):
"""Set up the user interface."""
# Main frame
main_frame = ttk.Frame(self.root, padding="10")
main_frame.pack(fill=tk.BOTH, expand=True)
# Input files frame
input_frame = ttk.LabelFrame(main_frame, text="Input CSV Files", padding="5")
input_frame.pack(fill=tk.X, padx=5, pady=5)
self.files_listbox = tk.Listbox(input_frame, height=5, selectmode=tk.EXTENDED)
self.files_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
scrollbar = ttk.Scrollbar(input_frame, orient=tk.VERTICAL, command=self.files_listbox.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y, padx=(0, 5), pady=5)
self.files_listbox.config(yscrollcommand=scrollbar.set)
# Buttons for input files
input_buttons_frame = ttk.Frame(main_frame)
input_buttons_frame.pack(fill=tk.X, padx=5, pady=(0, 5))
ttk.Button(input_buttons_frame, text="Add Files", command=self.add_files).pack(side=tk.LEFT, padx=5)
ttk.Button(input_buttons_frame, text="Remove Selected", command=self.remove_files).pack(side=tk.LEFT, padx=5)
ttk.Button(input_buttons_frame, text="Clear All", command=self.clear_files).pack(side=tk.LEFT, padx=5)
# Output directory
output_frame = ttk.LabelFrame(main_frame, text="Output Directory", padding="5")
output_frame.pack(fill=tk.X, padx=5, pady=5)
self.output_var = tk.StringVar()
ttk.Entry(output_frame, textvariable=self.output_var, state="readonly").pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
ttk.Button(output_frame, text="Browse...", command=self.select_output_dir).pack(side=tk.RIGHT, padx=5, pady=5)
# Options Frame
options_frame = ttk.LabelFrame(main_frame, text="Options", padding="5")
options_frame.pack(fill=tk.X, padx=5, pady=5)
self.debug_var = tk.BooleanVar(value=False)
ttk.Checkbutton(options_frame, text="Debug Mode", variable=self.debug_var).pack(anchor=tk.W, padx=5, pady=5)
# Convert button
ttk.Button(main_frame, text="Convert", command=self.start_conversion).pack(fill=tk.X, padx=5, pady=5)
# Progress bar
self.progress_var = tk.DoubleVar()
self.progress = ttk.Progressbar(main_frame, variable=self.progress_var, maximum=100)
self.progress.pack(fill=tk.X, padx=5, pady=5)
# Log frame
log_frame = ttk.LabelFrame(main_frame, text="Conversion Log", padding="5")
log_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.log_text = tk.Text(log_frame, wrap=tk.WORD, state="disabled")
self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
log_scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
log_scrollbar.pack(side=tk.RIGHT, fill=tk.Y, padx=(0, 5), pady=5)
self.log_text.config(yscrollcommand=log_scrollbar.set)
# Status bar
self.status_var = tk.StringVar()
self.status_var.set("Ready")
ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W).pack(side=tk.BOTTOM, fill=tk.X)
def add_files(self):
"""Add CSV files to the list."""
files = filedialog.askopenfilenames(
title="Select CSV Files",
filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")]
)
if files:
new_files = [f for f in files if f not in self.input_files]
self.input_files.extend(new_files)
# Update listbox
self.files_listbox.delete(0, tk.END)
for file in self.input_files:
self.files_listbox.insert(tk.END, os.path.basename(file))
self.status_var.set(f"{len(self.input_files)} files selected")
def remove_files(self):
"""Remove selected files from the list."""
selected_indices = self.files_listbox.curselection()
if not selected_indices:
return
# Remove files from the end to avoid index shifting
for idx in sorted(selected_indices, reverse=True):
del self.input_files[idx]
self.files_listbox.delete(idx)
self.status_var.set(f"{len(self.input_files)} files selected")
def clear_files(self):
"""Clear all files from the list."""
self.input_files = []
self.files_listbox.delete(0, tk.END)
self.status_var.set("Ready")
def select_output_dir(self):
"""Select output directory."""
directory = filedialog.askdirectory(title="Select Output Directory")
if directory:
self.output_dir = directory
self.output_var.set(directory)
def start_conversion(self):
"""Start the conversion process in a separate thread."""
if not self.input_files:
messagebox.showwarning("No Input Files", "Please select at least one CSV file to convert.")
return
if not self.output_dir:
messagebox.showwarning("No Output Directory", "Please select an output directory.")
return
# Check if converter module exists
converter_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "csv_to_word.py")
if not os.path.exists(converter_path):
messagebox.showerror("Error", "Converter module 'csv_to_word.py' not found. Please ensure it's in the same directory.")
return
# Redirect stdout to log
sys.stdout = RedirectText(self.log_text)
# Clear log
self.log_text.configure(state="normal")
self.log_text.delete(1.0, tk.END)
self.log_text.configure(state="disabled")
# Update status
self.status_var.set("Converting...")
# Start conversion in a separate thread
Thread(target=self.convert_files, daemon=True).start()
def convert_files(self):
"""Convert files using the converter module."""
try:
# Import converter module
spec = importlib.util.spec_from_file_location(
"csv_to_word",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "csv_to_word.py")
)
converter_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(converter_module)
# Process each file
total_files = len(self.input_files)
for i, file_path in enumerate(self.input_files):
# Update progress
file_progress = (i / total_files) * 100
self.progress_var.set(file_progress)
self.root.update_idletasks()
# Get output filename
base_filename = os.path.splitext(os.path.basename(file_path))[0]
output_path = os.path.join(self.output_dir, f"{base_filename}_regenerated.docx")
# Log
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"\n[{timestamp}] Processing file {i+1}/{total_files}: {os.path.basename(file_path)}")
# Convert file
try:
# Read CSV data
data = converter_module.read_csv_data(file_path)
# Group data hierarchically
hierarchy = converter_module.group_data_hierarchically(data)
# Create Word document
converter_module.create_word_document(hierarchy, output_path)
print(f"[{timestamp}] Successfully converted {os.path.basename(file_path)}")
print(f"[{timestamp}] Saved to {output_path}")
except Exception as e:
print(f"[{timestamp}] Error converting {os.path.basename(file_path)}: {str(e)}")
print(traceback.format_exc())
# Complete
self.progress_var.set(100)
self.status_var.set("Conversion complete")
# Show completion message
self.root.after(0, lambda: messagebox.showinfo("Conversion Complete",
f"Successfully converted {total_files} file(s) to Word format."))
except Exception as e:
# Handle any unexpected errors
print(f"Unexpected error: {str(e)}")
print(traceback.format_exc())
self.status_var.set("Error during conversion")
# Show error message
self.root.after(0, lambda: messagebox.showerror("Error", f"An error occurred: {str(e)}"))
finally:
# Reset stdout
sys.stdout = sys.__stdout__
def main():
"""Run the converter application."""
root = tk.Tk()
app = CSVToWordConverterApp(root)
root.mainloop()
if __name__ == "__main__":
main()