批量将MS Word表单转为TXT文件及自动化流程求助
Absolutely! Since you have Python experience, we can fully automate the first three steps (and even streamline the Excel import) using Windows COM automation and basic file handling. Let’s walk through a practical, step-by-step solution:
1. Automate Word Form Export to Delimited Text Files
We’ll use the pywin32 library to control Microsoft Word programmatically—this lets us replicate your manual workflow (open docs, enable "save only form data", export to TXT, skip popups) at scale.
First, install the required package:
pip install pywin32
Here’s the script to batch-export your Word forms:
import os import win32com.client as win32 from win32com.client import constants def export_word_forms(source_folder, output_folder): # Create output folder if it doesn't exist if not os.path.exists(output_folder): os.makedirs(output_folder) # Initialize Word application (run in background) word = win32.gencache.EnsureDispatch("Word.Application") word.Visible = False word.DisplayAlerts = constants.wdAlertsNone # Auto-skip all confirmation popups try: # Loop through all Word documents in the source folder for filename in os.listdir(source_folder): if filename.lower().endswith(('.doc', '.docx')): doc_path = os.path.join(source_folder, filename) txt_filename = f"{os.path.splitext(filename)[0]}.txt" txt_output_path = os.path.join(output_folder, txt_filename) # Open the document doc = word.Documents.Open(doc_path) # Save ONLY form data as delimited text doc.SaveAs2( FileName=txt_output_path, FileFormat=constants.wdFormatText, SaveFormsData=True, # This replicates the "Save only form data" option Encoding=constants.msoEncodingUTF8 # Uncomment below if you need to specify a custom delimiter (e.g., comma) # Separator=',' ) # Close the document without saving changes to the original Word file doc.Close(constants.wdDoNotSaveChanges) print(f"Successfully exported: {filename}") except Exception as e: print(f"Failed to process {filename}: {str(e)}") finally: # Clean up: quit Word to avoid lingering background processes word.Quit() # Replace these paths with your actual folders SOURCE_DIR = r"C:\Path\To\Your\Word\Forms" OUTPUT_TXT_DIR = r"C:\Path\To\Save\TXT\Files" export_word_forms(SOURCE_DIR, OUTPUT_TXT_DIR)
2. Automate Merging All TXT Files
Next, we’ll combine all exported TXT files into a single file—no need for cmd anymore. Add this function to your script:
def merge_txt_files(input_folder, merged_output_path): # Get all TXT files in the output folder txt_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.txt')] with open(merged_output_path, 'w', encoding='utf-8') as merged_file: # Optional: Write header once (if all forms have identical headers) # with open(os.path.join(input_folder, txt_files[0]), 'r', encoding='utf-8') as first_file: # merged_file.write(first_file.readline()) # Loop through files and write content (skip headers if you wrote them above) for txt_file in txt_files: file_path = os.path.join(input_folder, txt_file) with open(file_path, 'r', encoding='utf-8') as infile: lines = infile.readlines() # Uncomment below to skip duplicate headers # merged_file.writelines(lines[1:]) # Keep this line if there are no headers or you want all lines merged_file.writelines(lines) print(f"Merged: {txt_file}") # Replace with your desired merged file path MERGED_TXT_PATH = r"C:\Path\To\Merged\forms_merged.txt" merge_txt_files(OUTPUT_TXT_DIR, MERGED_TXT_PATH)
3. (Optional) Automate Excel Import & Cleaning
Since you plan to import into Excel, we can skip manual import by using pandas to convert the merged TXT directly to a cleaned Excel file. Install the extra packages first:
pip install pandas openpyxl
Add this final function:
import pandas as pd def txt_to_clean_excel(txt_path, excel_output_path): # Adjust the separator (sep) to match your delimited text (e.g., '\t' for tab, ',' for comma) df = pd.read_csv(txt_path, sep='\t', encoding='utf-8') # Optional: Add your data cleaning steps here # df = df.dropna() # Remove rows with empty values # df.rename(columns={"OldName": "NewName"}, inplace=True) # Rename columns # Save to Excel df.to_excel(excel_output_path, index=False, engine='openpyxl') print(f"Clean Excel file saved to: {excel_output_path}") # Replace with your desired Excel file path FINAL_EXCEL_PATH = r"C:\Path\To\Final\Clean_Forms.xlsx" txt_to_clean_excel(MERGED_TXT_PATH, FINAL_EXCEL_PATH)
Key Notes
- Test with a small batch of documents first to ensure the export settings match your manual workflow.
- Ensure Microsoft Word is installed locally—
pywin32relies on Word’s COM object to function. - If your forms have varying structures, you’ll need to add extra checks (e.g., validate column counts) to avoid merging errors.
内容的提问来源于stack exchange,提问作者Colin Chun-Kit Chan

