A method and system for intelligently generating word documents for construction organization design
By adopting Python-docx and PyQt5 technologies in the field of construction engineering, establishing preset templates and using placeholders to replace project feature information, combined with web-based editing and communication settings, the problems of poor template reusability and low collaboration efficiency in construction document editing are solved, and the intelligent and standardized generation of construction organization design and special construction plans is realized, which improves compilation efficiency and ensures document quality.
Patent Information
- Application Number
- CN202510905051.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-02
- Publication Date
- 2025-09-12
- Estimated Expiration
- 2045-07-02
AI Technical Summary
In the field of construction engineering, there are problems in the editing of construction documents, such as poor template reusability, inconsistent formats, low collaboration efficiency, low compilation efficiency and version conflicts. Especially when multiple people collaborate to compile construction organization designs and special construction plans, it is difficult to achieve standardization and efficient generation.
Using deep integration technology based on Python-docx and PyQt5, we create preset templates and use placeholders to replace project feature information content. Combined with web-based editing and communication settings, we can achieve intelligent insertion of project feature information and automatic filling of cover pages, forming standardized construction organization design or special construction plan documents.
It has realized the intelligent and standardized generation of construction organization design and special construction plans, improved the compilation efficiency by more than 5 times, ensured the consistency of document format and the efficiency of multi-person collaborative editing, and reduced the difficulty of data preparation and the risk of version conflicts.
Smart Images

Figure CN120409435B_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the interdisciplinary technical field of construction engineering informatization and intelligent document processing, and specifically relates to a method and system for intelligently generating word documents for construction organization design based on deep integration of Python-docx and PyQt5. The method and system are particularly suitable for the intelligent generation of standardized documents such as construction organization design and special construction plans in the field of construction engineering. Background Art
[0002] The objects targeted by construction organization design in the field of housing construction projects can be simply divided into: residential projects, public concrete projects, public steel structure projects, concrete structure factory projects and steel structure factory projects according to their purpose and structural type. Special construction plans can be simply divided into: formwork projects, deep foundation pit projects, steel structure projects, scaffolding projects, decoration and renovation projects, lifting and hoisting, and lifting machinery installation and disassembly projects according to the sub-item categories and construction objects.
[0003] The preparation of construction organization design should be based on relevant technical standards and administrative normative documents. Its chapter contents should generally include: preparation basis, project overview, construction deployment, construction schedule and guarantee measures, construction preparation and main resource allocation plan, main construction plan and technical measures, quality management and control measures, production safety management and control measures, occupational health management and control measures, environmental protection management and control measures, civilized construction management and control measures, construction site layout and other contents.
[0004] The preparation of special construction plans should also be based on relevant technical standards and administrative normative documents. The chapter contents should include: project overview, preparation basis, construction plan, construction technology, construction guarantee measures, construction management and staffing and division of labor, acceptance requirements, emergency response measures, calculation books and related construction drawings, etc.
[0005] The preparation of various types of construction organization designs and special construction plans can be divided into fixed content, project characteristic information content, and project-specific content, from the perspective of compliance with technical regulations and contract performance requirements. Fixed content includes chapter structure, preparation basis, main construction processes, and specification clause requirements. Project characteristic information content that reflects the specific characteristics of the project includes project overview, construction schedule, main resource allocation plan, construction site layout, construction management of special plans, staffing and division of labor, calculation books, and related construction drawings. Project-specific content that targets special project circumstances and requirements includes quality improvement planning that meets contractual requirements, construction period assurance measures, safety assurance measures caused by the special environment surrounding the project, and special safety requirements for special construction plans tailored to the project's characteristics, reflecting the differentiated needs of the project.
[0006] The current construction document editing in the field of construction engineering has the following technical pain points: (1) Poor template reusability: different projects need to repeatedly edit the same chapter content, and existing technologies require repeated settings for enterprise-specific format requirements; (2) The standardization of paragraph text, pictures, and table styles is low, and the generated document formats are not uniform; (3) Low collaborative efficiency: there are no standardized compilation requirements when multiple people are involved, and habitual differences lead to a lot of rework and low efficiency; (4) Low compilation efficiency: a single person takes a long time to compile and cannot guide construction work in a timely manner; (5) Version conflicts: the contents of each version are confusing and prone to errors. Summary of the Invention
[0007] As mentioned in the previous background, the preparation of construction organization design or special construction plan for different projects of the same type of project has a technical pain point of having to repeatedly edit many identical paragraphs, while the content reflecting the project characteristic information has a certain regularity. The present invention combines the two, forms a standardized template based on fixed content, replaces the content reflecting the regularity of project characteristic information with corresponding placeholders, becomes a preset template, replaces the project characteristic information content with certain technical means, and then adds project characteristic content to the file with the replaced project characteristic information, thereby realizing a targeted construction organization design or special construction plan with guidance for engineering construction, reflecting the differentiated needs of the project. The present invention provides this method, which solves the technical problems of poor template reusability, chaotic format, low collaborative efficiency, low compilation efficiency, and version conflicts in the preparation of traditional construction plans on the basis of enterprise-level construction organization design standardization management. When multiple people collaborate to complete the structured project characteristic information content and project characteristic content in the prescribed format, the preparation of construction organization design or special construction plan can be completed quickly, and the efficiency is improved by more than 5 times.
[0008] To achieve the above objectives, the present invention adopts the following specific technical solutions.
[0009] In a first aspect, a method for intelligently generating a construction organization design Word document is provided, which comprises the following steps:
[0010] S1. Establish preset templates: Establish preset templates for various types of construction organization designs and special construction plans. The content structure of the preset templates includes fixed content and project characteristic information content represented by placeholders; establish preset templates for subsequent replacement of project characteristic information content and insertion of project characteristic content.
[0011] S2. Loading and displaying preset templates: select a preset template that matches the pre-generated scheme, load the preset template and display the fixed content and placeholder information of the preset template in the web view; the document types corresponding to the pre-generated scheme include two categories: construction organization design and special construction scheme, which are divided into multiple template types according to the project category or structure type, such as: residential project construction group template, public building concrete project construction group template, public building steel structure project construction group template, etc. for construction organization design; template engineering special scheme engineering template, deep foundation pit engineering special scheme template, steel structure engineering special scheme template, decoration and renovation engineering special scheme template, etc. for special construction scheme; select the corresponding document type and the corresponding preset template here; this step is to prepare for reading the placeholder information of the preset template, and it can also fully check whether the loaded template matches the pre-generated scheme.
[0012] S3. Data loading: Data from Excel files is read using the pandas library in Python. The Excel file type is determined based on keywords in the file name, and then the corresponding loading method is called. Data from each Excel file is verified to be non-null and then classified and stored in different dictionaries. Paragraph text and table cell text data are stored as placeholders and text content, while paragraph image data and table cell image data are stored as placeholders and their corresponding image paths, sizes, and style information.
[0013] S4. Placeholder replacement: traverse the paragraphs and tables in the preset template, search and automatically replace them according to the dictionary data of the corresponding placeholders; this step performs a one-time quick replacement operation of the placeholders of the project feature information content based on the preset template.
[0014] S5. Generate a temporary intermediate solution file: After executing the placeholder replacement, save the replaced document as a temporary intermediate solution file with a timestamp, save it as a temporary file and save it to the preset temporary folder, and record the temporary file path at the same time; this step ensures that the timestamp document after the placeholder replacement can be temporarily saved and can be accurately located in the preset temporary folder for subsequent editing of the inserted project feature content.
[0015] S6. Web-based editing communication settings: The system builds a visual environment by loading preset HTML templates, and implements insertion point settings through HTML div elements and CSS styles. When the insertion point is clicked, the JavaScript function triggers the custom editor: / / URL Scheme, and the EditorUrlSchemeHandler class processes the request to achieve front-end and back-end communication; by clicking the insertion point, the target paragraph is accurately located and elements such as text, pictures, and Excel tables are inserted; this step is the prerequisite for inserting project feature information editing into temporary intermediate solution files on a web-based basis, bypassing the conventional Web-native communication limitations and achieving precise "click-to-locate" mapping.
[0016] S7. Edit the temporary intermediate solution file: Use WordEditor to insert the project feature content into the temporary intermediate solution file to form the solution file to be generated. Specifically, it includes: loading and parsing the temporary intermediate solution file, visual insertion point positioning based on QWebEngineView, identifying the content type and performing the corresponding text, Excel table, and picture insertion operations, maintaining style consistency, and converting to HTML for preview through Pandoc, and finally saving the version as a temporary file; this step ensures that the project feature information content can be edited and customized in the document after the placeholder is replaced.
[0017] S8. Edit the cover information of the solution file to be generated: By identifying the placeholders in the document, replace them with the corresponding cover information, including automatic filling of the project name, unit engineering name and preparation date, as well as the insertion of the cover image; this step ensures that the cover information of the document can be automatically filled in, improving the professionalism, completeness and enterprise standardization of the document.
[0018] S9. Generate and save the final document: Preview the proposed document with the loaded cover information. Generate the final document from the temporary file using generate_from_temp. Output and save the document. The document content is loaded and processed, and saved with a file name that includes the project name, document type, and timestamp. This step ensures that the final document can be generated and output for user use.
[0019] Furthermore, the preset template in S1 contains four types of placeholders: paragraph text placeholder, paragraph image placeholder, table cell text placeholder, and table cell image placeholder; the preset template is loaded in S2 and displayed in a web view, specifically: after selecting the preset template, the preset template is loaded from the specified path, the preset template is converted into HTML format using the Pandoc tool, and displayed through the QWebEngineView component, the fixed content and placeholder tags in the preset template are retained, and CSS styles are applied to ensure that the table and image are presented correctly, and the display effect is dynamically enhanced through JavaScript after loading is completed; the data in S3 is loaded, and the paragraph text placeholder and table cell text placeholder are loaded by reading "placeholder " and "text" columns to build the text_replacements dictionary. For paragraph image placeholders and table cell image placeholders, the "placeholder", "path", "width_cm", and "height_cm" columns are read to build the image_replacements dictionary. During the loading process, the successfully loaded files and the error messages of the failed loading are recorded to ensure the integrity and accuracy of the data, and finally form a complete dictionary data containing the placeholder name and the corresponding content; the placeholder replacement in S4 is processed by traversing the paragraphs and table cells in the preset template and using replace_paragraph_text_optimized() to process the paragraph text placeholder replacement: first save the first run of the paragraph Style, build new text after checking the placeholder, handle special date formats, clear the original run and insert new text with the first run style, use replace_paragraph_image_optimized() to traverse the image configuration, parse the path and use PIL to get the size, create a new paragraph and insert the image in the center, calculate the height according to the width, clear the original placeholder, use replace_table_text() to replace the table text according to the paragraph text placeholder replacement logic; use replace_table_image() to clear the placeholder first, parse the path to calculate the size, and insert the cell according to the configured width and alignment. All replacements are based on the PlaceholderDataLoader dictionary data, automatically handling relative path conversion and style inheritance.
[0020] The structured Excel data file in step S3 is pre-stored in a preset folder. The first row of the paragraph text .xlsx or table text .xlsx file is a four-column header of placeholder, text, font, and zize. The first column of the second row is a paragraph or table text placeholder, such as {{paragraph:text-1}} or {{table:text-1}}. The second row and second column are the text content to be replaced. The third and fourth columns of the second row are the corresponding styles of the font to be replaced, and the same applies to other rows. The first row of the paragraph image .xlsx or table image .xlsx file is a placeholder, path, Width-cm (image width, unit: cm), Height-cm (image height, unit: cm), Alignment (alignment) five column headers, the first column of the second row is the paragraph or table image placeholder, such as {{paragraph:image-1}} or {{table:image-1}}, the second example of the second row is the specific location and format of the image in the system, such as . / images / 2.PNG, the third, fourth and fifth columns of the second row are the image size and symmetry, such as 15.75x13.65, center (center), and so on for other rows.
[0021] Furthermore, the placeholder replacement in S4 is specifically as follows:
[0022] Placeholder replacement traverses the paragraphs and table cells in the preset template and performs precise matching based on the dictionary data loaded by PlaceholderDataLoader. If the replacement fails, the placeholder is retained and an error message is added to ensure the reliability of document generation. The four types of placeholder replacement are:
[0023] The paragraph text placeholder is processed by `_replace_paragraph_text_optimized()`: the style of the first run of the paragraph is saved first, the new text is constructed after checking the placeholder, special date format is automatically converted to Chinese format, all runs of the original paragraph are cleared, and the new text is injected with the style of the first run and inherits the original style;
[0024] Paragraph image placeholders are processed using `_replace_paragraph_image_optimized()`: the image replacement configuration is traversed, the image path is parsed, the dimensions are obtained using the PIL library, and the height is calculated. A new paragraph is created specifically for the image, which is inserted in a centered manner. The image width is set and the height is calculated proportionally. The original placeholder is cleared. If the process fails, the placeholder is retained and an error message is added.
[0025] The table cell image placeholder is processed through `_replace_table_image()`: first clear the cell placeholder, parse the image path to get the actual size and calculate the height according to the configured width, insert it into the table cell according to the specified alignment, and add error prompt text if the image fails to load;
[0026] The table cell text placeholder is processed by `_replace_table_text()`: it traverses the table cells, retains the original style of the first run, clears the placeholder content, builds new text and handles special date formats, clears the original run and injects the new text with the first run style to ensure consistent style;
[0027] Furthermore, S5 generates a temporary intermediate solution file. Specifically, after the placeholder replacement is completed, datetime.now().strftime("%Y%m%d_%H%M%S") is called to generate a timestamp. The timestamp is converted to the "year-month-day_hour-minute-second" format using strftime("%Y%m%d_%H%M%S"), and a temporary file named "intermediate solution_timestamp.docx" is created in the project's temp subdirectory, ensuring that each temporary file has a unique identifier. The temporary file is saved and the temporary file path is recorded, which is stored in the instance variable temp_file. The document object with the completed placeholder replacement is persisted to this path using the doc.save() method of the docx library. The integrity of the original document format and the replaced content is strictly maintained during the process. The absolute path of the generated temporary file is simultaneously stored in the instance variable temp_file. This variable serves as a key status identifier, providing a unified file access entry for subsequent operations such as document preview, secondary editing, and final version generation. The automatic cleanup mechanism for temporary files is triggered after the final document is generated, effectively managing storage space.
[0028] Furthermore, the web-based editing communication settings in the S6 are as follows: after loading the temporary intermediate solution file through the python-docx library, use enumerate(paragraphs) and enumerate(tables) to generate consecutive ID identifiers for document paragraphs and tables for front-end interactive positioning; in the HTML conversion stage, preset insertion point divs before the ordinary paragraph after the first level title paragraph, after the end of the table, and at the beginning of the document, and automatically insert divs with CSS styles at the beginning of the document (id="doc_start_point") and between each chapter through the _generate_html_with_insertion_points() method. <div class=""insert-point”">Visual markup: Build an HTML visual editing interface based on the QWebEngineView component, register a custom URL protocol using QWebEngineUrlScheme.registerScheme, and establish a front-end and back-end communication channel through a custom editor: / / URL Scheme. When the insertion point is clicked in the HTML interface, the front-end JavaScript triggers an editor: / / / select request through the selectElement() function and carries the target paragraph ID parameter. The back-end captures the request and parses the parameters through the EditorUrlSchemeHandler class implemented by inheriting QWebEngineUrlSchemeHandler. The handle_element_selected method of DocumentController updates the current selected paragraph status. The current selected paragraph status includes displaying the unique ID of the currently selected position in the status panel and visually highlighting the target paragraph. This step builds a visual editing interface through HTML and uses a custom "editor: / / URL Scheme" to establish an efficient communication mechanism, breaking through the interaction limitations of traditional Web and native applications. A virtual URL bridges the Web interface and the Document Object Model, enabling Web-based precise editing of temporary intermediate solution files. This maintains the visual advantages of the browser environment while achieving native application-level document operation accuracy. When clicking a specific insertion point in the interface, the system frontend captures the element ID via JavaScript and triggers an "editor: / / / select" request. The backend parses the request parameters via "EditorUrlSchemeHandler," accurately mapping the target paragraph location to the corresponding node in the Document Object Model (DOM), establishing a real-time, "click-to-locate" editing channel. This communication mechanism serves as the core premise, enabling insertion operations of text, images, and Excel tables in the HTML interface to precisely affect the underlying docx document structure: inserted text inherits the target paragraph's style attributes, images automatically adapt to cell size and maintain a wrap-around layout, and Excel tables are converted to native Word tables via OpenXML, preserving formulas and formatting. Ultimately, a closed-loop "what you see is what you get—what you click is what you change" workflow is established during the web-based editing phase of temporary files, providing a reliable technical foundation for the dynamic injection of project-specific information.
[0029] Furthermore, the insertion of the project characteristic information content into the temporary intermediate solution file by WordEditor in S7 is specifically as follows:
[0030] The WordEditor component is used to edit the project-specific content of the temporary intermediate solution file. First, the temporary intermediate solution file with placeholder replacement has been loaded and parsed, and a two-way mapping relationship between the document object model and the visual editing interface is established. The insertion point precision positioning system is implemented based on the QWebEngineView visual interface. By rendering the document HTML preview and capturing click events, the interface coordinates are converted into the physical position index of the document paragraph / table. The system automatically identifies the type of content to be inserted: text / picture / table, and calls the corresponding insertion method. Text insertion uses python-docx's add_paragraph and add_run methods to retain the original format style. Picture insertion uses the add_picture method to achieve dynamic size adjustment and wrapping layout. Excel table insertion uses openpyxl to parse the data and dynamically generate a Word table while retaining the cell style. WordEditor uses QWebEngineView.setHtml to render the document content in real time, and combines MutationObserver to monitor DOM changes to ensure that the editing operation is synchronized with the underlying Word document object and saves the edited document to the solution file to be generated. All insertion operations are checked for format consistency through the Style Manager to ensure that the new content is compatible with the document's existing style system. After each edit is completed, a new version with a timestamp ("to be generated solution_timestamp.docx") is automatically generated, preserving the edit history while avoiding overwriting the original intermediate file.
[0031] Furthermore, temporary files are generated as follows: tempfile.mkstemp() is used to generate a temporary file with a random suffix during the document editing process. The system will create a subdirectory named temp under the program directory to store temporary files. When the user performs a save operation, a timestamp is generated and used to name the temporary file. The naming format of the temporary file is "intermediate solution_timestamp.docx" or "to be generated solution_timestamp.docx". The system ensures the existence of the temporary directory through os.makedirs and saves the current document content to the temporary file through the save method of the Document object; then the shutil.move() atomic operation is used to replace the target file to avoid document damage that may be caused by direct writing; the temporary file naming integrates the timestamp and process to ensure uniqueness, and the cleanup hook is registered through atexit to automatically delete residual files when the program exits abnormally. The WordEditor class manages temporary files through the TempFileManager module.
[0032] Furthermore, the final document generated in S9 is specifically generated by loading the temporary file "to be generated_timestamp.docx" and using the Document class to process the document content: the add_paragraph method is used to add or modify text content paragraph by paragraph, and the run.font property is simultaneously set to configure the font style; the add_table method is used to insert table content, including first obtaining the number of rows and columns of data before creating the table structure and filling the cell data through a double loop; the add_picture method is used to insert picture content, including verifying the image path and calculating the proportional scaling of the image size; during the document saving phase, the save method is called to save the document to the specified path. In the generate_from_temp method, the existence of the temporary file is first checked, the temporary document is loaded for processing, and finally saved to the output directory. The output path is generated using the get_output_path method. The save method is called during the document saving phase to implement the temporary file mechanism, first writing to the temporary file and then renaming it to the target file through an atomic operation. A try-except block is used to catch possible IOError and ValueError exceptions to ensure a safe rollback in the event of an operation failure.
[0033] In a second aspect, a system for intelligently generating Word documents for construction organization design is provided, comprising:
[0034] A preset template loading module is used to load various preset templates. The preset template document types are divided into two types: construction organization design and special construction plan. The preset template content structure includes fixed content and project feature information represented by placeholders;
[0035] The data loading module is used to read placeholder replacement data from an Excel file in a preset path, including paragraph text replacement data, paragraph image replacement data, table text replacement data, and table image replacement data;
[0036] The project feature information replacement module is used to traverse the project feature information placeholders in the preset template and automatically replace them to generate a temporary intermediate solution file, including:
[0037] The paragraph text replacement unit is used to perform text replacement operations on the paragraph text placeholder;
[0038] The paragraph image replacement unit is used to perform image replacement operations on paragraph image placeholders;
[0039] Table cell text replacement unit, used to perform table cell text replacement operations on table text placeholders;
[0040] Table cell image replacement unit, used to perform table cell image replacement operations on table image placeholders;
[0041] The project feature content insertion module is used to insert project feature information into the temporary intermediate solution file to form the solution file to be generated. This module includes: loading and parsing the temporary intermediate solution file, web-based editing communication settings, visual insertion point positioning based on QWebEngineView, content type identification and corresponding insertion, style consistency maintenance, and versioning.
[0042] The document preview module converts the loaded paragraphs and tables of the preset template into HTML format and loads them into the preview window through the setHtml method. CSS styles are applied to enhance the visual effect and achieve visual preview. A unique ID is assigned to each paragraph and table, and JavaScript is used to achieve real-time updates and interactions to highlight and scroll positioning of selected elements.
[0043] The cover processing module is used to process the document cover information of the generated solution file, including automatic filling of the project name, unit engineering name and preparation date, as well as the insertion of the cover image;
[0044] The document generation module is used to output the final Word document for the to-be-generated solution file with completed cover information.
[0045] This invention solves the problems of poor template reusability, confusing formats, low collaboration efficiency, low compilation efficiency, and version conflicts in traditional construction plan compilation. It realizes the intelligent and standardized generation of construction organization design documents. The editing of Excel structured data can realize multi-person collaborative data editing operations, significantly reducing the threshold for editing placeholder data using JSON key-value structures, greatly reducing the difficulty of data preparation for plan editors, improving team efficiency, and multi-person collaboration also improves data editing efficiency. The one-click placeholder replacement method provided by this invention increases the efficiency of plan editing by more than 5 times, ensuring standardized output and text quality of plan compilation. BRIEF DESCRIPTION OF THE DRAWINGS
[0046] Figure 1 Generate a flow chart for the document in the present invention;
[0047] Figure 2 This is a diagram of the table text data structure in the present invention;
[0048] Figure 3 This is a diagram of the data structure of a paragraph image in the present invention;
[0049] Figure 4 This is a workflow diagram of the document editor in the present invention;
[0050] Figure 5 This is a program architecture diagram of the present invention. DETAILED DESCRIPTION
[0051] To make the purpose, technical solutions, and advantages of the embodiments of the present invention more clear, the following will combine some codes and system operation interfaces in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of them.
[0052] Example 1:
[0053] like Figure 1 As shown, taking the residential project construction organization design as an example, a method for intelligently generating a Word document for the construction organization design includes the following steps:
[0054] S1. Establish preset templates: Establish preset templates for various types of construction organization designs and special construction plans. The content structure of the preset templates includes fixed content and project feature information content represented by placeholders; the preset templates contain four types of placeholders: paragraph text placeholders, paragraph image placeholders, table text placeholders, and table image placeholders.
[0055] S2. Loading and displaying preset templates: select the scheme type corresponding to the pre-generated scheme and the adapted preset template; load the preset template and display the fixed content and placeholder information of the preset template in the web view; specifically, for example: when preparing the construction organization design of a residential project, the document type should be selected as the construction organization design, and the preset template should be the residential project construction organization design template. After loading, the fixed content and placeholder information of the preset template can be displayed in the web view, and it can be clearly seen whether the loaded template matches the pre-generated residential project construction organization design.
[0056] S3. Data loading: Read the data from the Excel file using the pandas library in Python. First, determine the Excel file type based on the keywords in the Excel file name, and then call the corresponding loading method. After the data in each Excel file is checked for non-emptiness, it is classified and stored in different dictionaries: paragraph text and table cell text data are stored as dictionary data in the form of placeholders and text content, and paragraph images and table cell image data are stored as dictionary data in the form of placeholders and their corresponding image paths, sizes, and style information. The placeholder Excel file sheet data contains paragraph text .xlsx or table text .xl. The first line of the sx file contains the four column headers: placeholder, text, font, and zize. The first column of the second line contains the name of the paragraph or table cell text placeholder, such as {{paragraph:text-1}} or {{table:text-1}}. The second column of the second line contains the text to be replaced. The third and fourth columns of the second line contain the corresponding font styles to be replaced. The same applies to other lines. The first line of the paragraph image .xlsx or table cell image .xlsx file contains the placeholder, path, width-cm (image width, unit: cm), Height-cm (image height, unit: cm), Alignment (alignment) five column headers, the second row and the first column is the paragraph or table cell image placeholder name, such as {{paragraph:image-1}} or {{table:image-1}}, the second row and the second column is the specific location and format of the image path, such as . / images / 2.PNG, the third, fourth and fifth columns of the second row are the image size and symmetry, such as 15.75x13.65, center (center), and the data in other rows are similar.
[0057] S4. Placeholder replacement: traverse the paragraphs and tables in the preset template, search and automatically replace them according to the dictionary data of the corresponding placeholders; this step performs a one-time quick replacement operation of the placeholders of the project feature information content based on the preset template. Placeholder replacement includes: performing paragraph text replacement operations on paragraph text placeholders, performing paragraph image replacement operations on paragraph image placeholders, performing table cell text replacement operations on table cell text placeholders, and performing table cell image replacement operations on table cell image placeholders. When performing replacement, perform paragraph text replacement operations on paragraph text placeholders: use _replace_paragraph_text_optimized() to first save the style baseline of the first run of the paragraph, build new text through placeholder matching, automatically process special date formats and convert them into Chinese format, clear all runs of the original paragraph, inject new text with the first run style and inherit the original style; perform paragraph image replacement operations on paragraph image placeholders: use _replace_paragraph_image_optimized() to traverse the image configuration, parse the path, use the PIL library to obtain the size and calculate the height according to the configured width, create a new paragraph to specifically place the image, insert it in a centered alignment and set the size, clear the original placeholder, and if the processing fails, retain the placeholder and add an error prompt; Perform table cell text replacement on table cell text placeholders: use _replace_table_text(), the logic is consistent with paragraph text replacement, retain the original style of the first run when traversing table cells, process placeholder text and special date formats, clear the original run, inject new text and inherit the style; perform table cell image replacement on table cell image placeholders: first clear the cell placeholder through _replace_table_image(), parse the image path to obtain the actual size and calculate the height according to the configured width, insert it into the table cell according to the specified alignment, and add error prompt text if the image fails to load.
[0058] S5. Generate a temporary intermediate solution file: After executing the placeholder replacement, save the replaced document as a temporary intermediate solution file with a timestamp, save it as a temporary file and save it to the preset temporary folder, and record the temporary file path at the same time; this step ensures that the timestamp document after the placeholder replacement can be temporarily saved and can be accurately located in the preset temporary folder for subsequent editing of the inserted project feature content. After the placeholder replacement operation is completed, storage space is automatically created in the temp subdirectory of the project root directory (if it does not exist, a new one will be created). Then, a complete file path is constructed using the naming convention of "intermediate solution_timestamp.docx". A temporary document path containing a timestamp (formatted as "year-month-day-hour-minute-second") is dynamically constructed using the _generate_output_path() method. A timestamp accurate to the second is generated by calling datetime.now().strftime("%Y%m%d_%H%M%S") and formatted into the standard string format of "year-month-day-hour-minute-second" to ensure that each temporary file has a unique identifier. The document object with completed placeholder replacement is persisted to the path using the docx library's doc.save() method. The integrity of the original document format and the replaced content is strictly maintained during the process. The generated temporary file's absolute path is simultaneously stored in the instance variable temp_file. This variable serves as a key status identifier, providing a unified file access entry for subsequent document preview, secondary editing, and final version generation.
[0059] S6. Web-based editing communication settings: In the web-based editing interface, the insertion point is set using HTML div elements and CSS styles. When the insertion point is clicked, a JavaScript function triggers a custom editor: / / URL scheme, which is then processed by the EditorUrlSchemeHandler class to achieve front-end and back-end communication. Clicking the insertion point allows for precise positioning of the target paragraph and insertion of elements such as text, images, and Excel tables. This step is the prerequisite for inserting project feature information into a temporary intermediate solution file on a web-based basis, bypassing conventional web-native communication limitations and achieving precise "click-to-locate" mapping. After loading the temporary intermediate solution file through the python-docx library, enumerate(paragraphs) and enumerate(tables) are used to generate consecutively numbered ID identifiers for document paragraphs and tables, such as para_0 and table_1, for front-end interactive positioning; during the HTML conversion phase, an insertion point div is preset before the ordinary paragraph after the first level-one heading paragraph, after the end of the table, and at the beginning of the document. Visual feedback is achieved through basic CSS: .insert-point:hover changes the background color, and the .active-insert class uses keyframe animation to achieve a pulse border effect; the communication layer uses PyQt5's standard implementation solution: QWebEngineUr When the lSchemeHandler subclass processes the editor: / / protocol request, it directly forwards the paragraph ID to the main window slot function through QTimer.singleShot (without QByteArray to encapsulate complex parameters); the actual workflow of the positioning system is: the front-end click triggers selectElement() to send a URL request containing para_id → the back-end EditorUrlSchemeHandler parses the ID → WordEditor.highlight_selected() performs three steps through runJavaScript: clear the old highlight → locate the target insertion point → add the .active-insert class and trigger smooth scrolling.
[0060] S7. Edit the temporary intermediate solution file: Use WordEditor to insert the project feature content into the temporary intermediate solution file to form the solution file to be generated, specifically including: loading and parsing the temporary intermediate solution file, positioning the visual insertion point based on QWebEngineView, identifying the content type and performing the corresponding text, Excel table, and picture insertion operations, maintaining style consistency, and converting to HTML for preview through Pandoc, and finally saving the version as a temporary file; first load and parse the temporary intermediate solution file that has completed placeholder replacement, and build a two-way mapping relationship between the document object model and the visual editing interface; implement the insertion point precise positioning system based on the visual interface of QWebEngineView, and convert the interface coordinates into the physical position index of the document paragraph / table by rendering the document HTML preview and capturing click events; the system automatically identifies the content type to be inserted (text / picture / table) and calls the corresponding insertion method - the text content inherits the font style attributes of the target paragraph, the picture automatically calculates the aspect ratio and applies the preset wrapping format, and the Excel table is converted into the native Word table structure after being parsed by openpyxl; all insertion operations are performed through The style manager enforces format consistency verification to ensure that new content is compatible with the document's existing style system. After each edit, a new version with a timestamp is automatically generated ("to be generated solution_timestamp.docx"), preserving the edit history while avoiding overwriting the original intermediate file. This process uses atomic operations to ensure that even in the event of an abnormal interruption, it can roll back to the most recent valid version, achieving a safe evolution from temporary files to the final solution. Specifically, text is inserted using python-docx's add_paragraph and add_run methods to retain the original formatting style. Image insertion uses the add_picture method to achieve dynamic resizing and wrapping layout (using OxmlElement to operate on XML and set the wrap attribute). Excel tables are dynamically generated into Word tables (doc.add_table) after parsing data using openpyxl, preserving cell styles. The editor uses QWebEngineView.setHtml to render document content in real time, and combines MutationObserver to monitor DOM changes to ensure that editing operations are synchronized with the underlying Word document object, and the edited document is saved to the to be generated solution file.
[0061] S8. Edit the cover information of the solution file to be generated: by identifying the placeholders in the document, replace them with the corresponding cover information, including automatic filling of the project name, unit project name and compilation date, and inserting the cover image; by parsing the input project name, unit project name, compilation date and cover image path, locate the predefined placeholders {{title-1}}, {{title-2}}, {{yyyy-mm-dd-1}} and {{image:fm-1}} corresponding to the project name, unit project name and compilation date in the document and replace them. For the cover image placeholder, the system first verifies The image path is validated. If it exists, the placeholder paragraph content is cleared and the specified image is inserted. The image width is set to 6 inches and the image is centered. If the image does not exist, the placeholder text is retained. In the UI dialog, the digitized Gregorian calendar date is converted to Chinese capitalization using the convert_calendar_date() function, such as "May 10, 2025." All style modifications are applied directly to the paragraph Run object to maintain the original formatting characteristics of the template. The processing status is recorded in the logging module. This step ensures that the document cover information is automatically filled, improving the standardization, completeness, and corporate standardization of the cover information. After loading the cover information, the generated solution file can be previewed in the next step.
[0062] S9. Generate and save the final document: Preview the proposed document with the loaded cover information, generate the final document from the temporary file using generate_from_temp, output it, and save it. Load and process the document content, and save it as a file name containing the project name, document type, and timestamp. By parsing the XML structure of a Word document, the paragraph text and style attributes are extracted to generate visual content, and images are referenced and displayed as temporary files. When generating a document, placeholders such as {{title-1}} are precisely located and replaced with content. The font, size, and bold style of the original template are maintained through the font property of paragraph.runs. Table processing uses doc.add_table to create the basic structure, then fills the data cell by cell and copies style attributes such as bold and border. Image insertion strictly verifies the validity of the file path and supports encoding conversion. The height is automatically calculated proportionally to the specified width and then embedded through run.add_picture. When saving documents, the naming convention of "Unit Project Name_Document Type_Timestamp.docx" is used, such as "Building 1 Main Structure Project_Construction Group_20240101_120000.docx", where the document type is automatically converted to "Construction Group" or "Special Construction Plan". The timestamp is accurate to the second to ensure uniqueness. Exception handling uses the logging module to record errors in file operations, image loading, and other processes without interrupting the process. The final document automatically adds a header containing the company logo. All operations are based on the direct modification of the Word document XML structure using the python-docx library, which not only maintains the original format characteristics of the template but also ensures the professionalism and standardization of the generated document.
[0063] A construction organization design Word document intelligent generation system, comprising:
[0064] A preset template loading module is used to load various preset templates. The preset template document types are divided into two types: construction organization design and special construction plan. The preset template content structure includes fixed content and project feature information represented by placeholders;
[0065] The data loading module is used to read placeholder replacement data from an Excel file in a preset path, including paragraph text replacement data, paragraph image replacement data, table text replacement data, and table image replacement data;
[0066] The project feature information replacement module is used to traverse the project feature information placeholders in the preset template and automatically replace the placeholder replacement data and generate a temporary intermediate solution file, including:
[0067] The paragraph text replacement unit is used to perform text replacement operations on the paragraph text placeholder;
[0068] The paragraph image replacement unit is used to perform image replacement operations on paragraph image placeholders;
[0069] Table cell text replacement unit, used to perform table cell text replacement operations on table text placeholders;
[0070] Table cell image replacement unit, used to perform table cell image replacement operations on table image placeholders;
[0071] The project feature content insertion module is used to insert project feature information content into the temporary intermediate solution file to form the solution file to be generated; it includes: loading and parsing the temporary intermediate solution file, web-based editing communication settings, visual insertion point positioning based on QWebEngineView, content type identification and corresponding insertion, style consistency maintenance, and versioning.
[0072] The document preview module converts the loaded paragraphs and tables of the preset template into HTML format and loads them into the preview window through the setHtml method. CSS styles are applied to enhance the visual effect and achieve visual preview. A unique ID is assigned to each paragraph and table, and JavaScript is used to achieve real-time updates and interactions to highlight and scroll positioning of selected elements.
[0073] The cover processing module is used to process the document cover information of the generated solution file, including automatic filling of the project name, unit engineering name and preparation date, as well as the insertion of the cover image;
[0074] The document generation module is used to output the final Word document for the to-be-generated solution file with completed cover information.
[0075] Example 2:
[0076] Taking the template engineering special construction plan as an example, a method for intelligently generating a Word document for construction organization design includes the following steps:
[0077] S1. Establish preset templates: Establish preset templates for various types of construction organization designs and construction special plans. The content structure of the preset templates includes fixed content and project feature information content represented by placeholders; the preset templates contain four types of placeholders: paragraph text placeholders, paragraph image placeholders, table text placeholders, and table image placeholders.
[0078] S2. Loading and displaying preset templates: select the scheme type corresponding to the pre-generated scheme and the adapted preset template; load the preset template and display the fixed content and placeholder information of the preset template in the web view; specifically, for example: when preparing a special construction scheme for a template project, the document type should be selected as a special construction scheme, and the preset template should be selected as a template project special construction scheme template. After loading, the fixed content and placeholder information of the preset template can be displayed in the web view, and it can be clearly seen whether the loaded template matches the pre-generated special construction scheme for the template project.
[0079] The remaining steps are the same as those in Example 1.
[0080] Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without making any creative work shall fall within the scope of protection of the present invention.
Claims
1. A method for intelligently generating a word document for construction organization design, characterized in that: The following steps are involved: S1. Establishing preset templates: Establishing preset templates for various types of construction organization designs and special construction plans. The content structure of the preset templates includes fixed content and project feature information represented by placeholders; S2. Loading and displaying preset templates: Select a preset template that matches the pre-generated solution, load the preset template, and display the fixed content and placeholder information of the preset template in a web view; S3. Data loading: Data from Excel files is read using the pandas library. The Excel file type is first determined based on keywords in the Excel file name, and then the corresponding loading method is called. Data from each Excel file is verified to be non-null and then classified and stored in different dictionaries. Paragraph text and table cell text data are stored as dictionary data in the form of placeholders and text content. Paragraph image data and table cell image data are stored as dictionary data in the form of placeholders and their corresponding image paths, sizes, and style information. S4. Placeholder replacement: traverse the paragraphs and tables in the preset template, search and automatically replace the corresponding placeholders based on the dictionary data; S5. Generate a temporary intermediate solution file: After performing the placeholder replacement, save the replaced document as a temporary intermediate solution file with a timestamp to a preset temporary folder, and record the temporary file path; S6. Web-based editing communication settings: After loading the temporary intermediate solution file through the python-docx library, use enumerate(paragraphs) and enumerate(tables) to generate consecutive ID identifiers for document paragraphs and tables for front-end interactive positioning; in the HTML conversion stage, preset insertion point divs before the ordinary paragraph after the first level title paragraph, after the end of the table, and at the beginning of the document, and automatically insert div class="insert-point" visual tags with CSS style at the beginning of the document id="doc_start_point" and between each chapter through the _generate_html_with_insertion_points() method; build an HTML visual editing interface based on the QWebEngineView component, use QWebEngineUrlScheme.registerScheme to register a custom URL protocol, and customize the editor: / / URL Scheme establishes a front-end and back-end communication channel. When the insertion point is clicked in the HTML interface, the front-end JavaScript triggers the editor: / / / select request through the selectElement() function and carries the target paragraph ID parameter. The back-end captures the request and parses the parameters by inheriting the EditorUrlSchemeHandler class implemented by QWebEngineUrlSchemeHandler. The handle_element_selected method of DocumentController updates the status of the currently selected paragraph. The currently selected paragraph status includes displaying the unique ID of the currently selected position in the status panel and visually highlighting the target paragraph. S7. Editing the temporary intermediate solution file: Use WordEditor to insert project-specific content into the temporary intermediate solution file to form the solution file to be generated. This includes: loading and parsing the temporary intermediate solution file, visually locating the insertion point based on QWebEngineView, identifying the content type and inserting the corresponding text, Excel table, and image, maintaining style consistency, converting to HTML for preview using Pandoc, and finally saving the versioned file as a temporary file. S8. Edit the cover information of the proposed document to be generated: By identifying the placeholders in the document, it is replaced with the corresponding cover information, including automatic filling of the project name, unit engineering name and preparation date, as well as the insertion of the cover image; S9. Generate the final document and save it: Generate the final document based on the temporary file through generate_from_temp, output it and save it.
2. The method for intelligently generating a construction organization design Word document according to claim 1, characterized in that: The preset template in S1 contains four types of placeholders: paragraph text placeholder, paragraph image placeholder, table cell text placeholder, and table cell image placeholder; the preset template is loaded in S2 and displayed in a web view, specifically: after selecting a preset template, the preset template is loaded from the specified path, the preset template is converted into HTML format using the Pandoc tool, and displayed through the QWebEngineView component, the fixed content and placeholder tags in the preset template are retained, and CSS styles are applied to ensure that the table and image are presented correctly, and the display effect is dynamically enhanced through JavaScript after loading; the data in S3 is loaded, and the paragraph text placeholder and table cell text placeholder are loaded by reading "placeholdere The "r" and "text" columns are used to construct the text_replacements dictionary. For paragraph image placeholders and table cell image placeholders, the "placeholder", "path", "width_cm", and "height_cm" columns are read to construct the image_replacements dictionary. During the loading process, the successfully loaded files and the error messages of the failed loading are recorded to ensure the integrity and accuracy of the data, and finally a complete dictionary data containing the placeholder name and the corresponding content is formed; the placeholder replacement in S4 is performed by traversing the preset template paragraphs and table cells, using replace_paragraph_text_optimized() to process the paragraph text placeholder, retaining the first run style and handling special date formats; after using replace_paragraph_image_optimized() to parse the image path, a new paragraph is created to insert the image in the center, the height is calculated according to the size, the original placeholder is cleared, and the table text is processed according to the paragraph logic using replace_table_text(). Use replace_table_image() to first clear the placeholder, calculate the height according to the configured width, and insert the table cell according to the specified alignment. All replacements are based on PlaceholderDataLoader data, automatically handling relative path conversion and style inheritance.
3. The method for intelligently generating a construction organization design Word document according to claim 1, characterized in that: The S5 generates a temporary intermediate solution file, specifically: After the placeholder replacement is completed, call datetime.now().strftime("%Y%m%d_%H%M%S") to generate a timestamp, use strftime("%Y%m%d_%H%M%S") to convert the timestamp to the "year-month-day_hour-minute-second" format, and then create a temporary file named "intermediate solution_timestamp.docx" in the project's temp subdirectory, save the temporary file, and record the temporary file path, which is stored in the instance variable temp_file.
4. The method for intelligently generating a construction organization design Word document according to claim 1, wherein: The insertion of project characteristic information content into the temporary intermediate solution file by WordEditor in the S7 is specifically as follows: Text insertion uses python-docx's add_paragraph and add_run methods to retain the original formatting style. Image insertion uses the add_picture method to achieve dynamic size adjustment and wrapping layout. Excel table insertion uses openpyxl to parse data and dynamically generate a Word table while retaining the cell style. WordEditor uses QWebEngineView.setHtml to render document content in real time, combined with MutationObserver to monitor DOM changes, ensuring that editing operations are synchronized with the underlying Word document object and saving the edited document to the solution file to be generated.
5. The method for intelligently generating a construction organization design word document according to claim 1, characterized in that: The temporary file generation is as follows: During document editing, the system creates a subdirectory named temp in the program directory to store temporary files. When the user saves the document, a timestamp is generated and used to name the temporary file. The naming format of the temporary file is "intermediate solution_timestamp.docx" or "to-be-generated solution_timestamp.docx". The system uses os.makedirs to ensure the existence of the temporary directory and saves the current document content to the temporary file through the save method of the Document object.
6. The method for intelligently generating a construction organization design word document according to claim 5, characterized in that: The final document is generated in S9 specifically as follows: by loading the "to be generated scheme_timestamp.docx" temporary file, the Document class is used to process the document content: the text content is added or modified paragraph by paragraph through the add_paragraph method, and the run.font property is simultaneously set to configure the font style; the table content is inserted through the add_table method, including first obtaining the number of rows and columns of data and then creating the table structure, and filling the cell data through a double loop; the picture content is inserted through add_picture, including the verification of the picture path and the proportional scaling calculation of the size; in the document saving link, the save method is called to save the document to the specified path. In the generate_from_temp method, first check whether the temporary file exists, then load the temporary document for processing, and finally save it to the output directory. The output path is generated by the get_output_path method.
7. A construction organization design word document intelligent generation system, characterized by: include: A preset template loading module is used to load various preset templates. The preset template document types are divided into two types: construction organization design and special construction plan. The preset template content structure includes fixed content and project feature information represented by placeholders; The data loading module is used to read placeholder replacement data from an Excel file in a preset path, including paragraph text replacement data, paragraph image replacement data, table text replacement data, and table image replacement data; The project feature information replacement module is used to traverse the project feature information placeholders in the preset template and automatically replace the placeholder replacement data and generate a temporary intermediate solution file, including: The paragraph text replacement unit is used to perform text replacement operations on the paragraph text placeholder; The paragraph image replacement unit is used to perform image replacement operations on paragraph image placeholders; Table cell text replacement unit, used to perform table cell text replacement operations on table text placeholders; Table cell image replacement unit, used to perform table cell image replacement operations on table image placeholders; The project feature content insertion module is used to insert project feature information content into the temporary intermediate solution file to form the solution file to be generated; it includes: loading and parsing the temporary intermediate solution file, web-based editing communication settings, visual insertion point positioning based on QWebEngineView, identifying content types and executing corresponding text, Excel table, and image insertion operations, maintaining style consistency, and converting to HTML through Pandoc for preview, and finally saving the version as a temporary file; The specific settings for web-based editing communication are: After loading the temporary intermediate solution file through the python-docx library, use enumerate(paragraphs) and enumerate(tables) to generate consecutive ID identifiers for document paragraphs and tables for front-end interactive positioning; in the HTML conversion stage, preset insertion point divs before the ordinary paragraph after the first level title paragraph, after the table, and at the beginning of the document, and automatically insert div class="insert-point" visual markers with CSS style at the beginning of the document id="doc_start_point" and between each chapter through the _generate_html_with_insertion_points() method; build an HTML visual editing interface based on the QWebEngineView component, use QWebEngineUrlScheme.registerScheme to register a custom URL protocol, and customize the editor: / / URL Scheme establishes a front-end and back-end communication channel. When the insertion point is clicked in the HTML interface, the front-end JavaScript triggers the editor: / / / select request through the selectElement() function and carries the target paragraph ID parameter. The back-end captures the request and parses the parameters by inheriting the EditorUrlSchemeHandler class implemented by QWebEngineUrlSchemeHandler. The handle_element_selected method of DocumentController updates the status of the currently selected paragraph. The currently selected paragraph status includes displaying the unique ID of the currently selected position in the status panel and visually highlighting the target paragraph. The document preview module converts the loaded paragraphs and tables of the preset template into HTML format and loads them into the preview window through the setHtml method. CSS styles are applied to enhance the visual effect and achieve visual preview. A unique ID is assigned to each paragraph and table, and JavaScript is used to achieve real-time updates and interactions to highlight and scroll positioning of selected elements. The cover processing module is used to process the document cover information of the generated solution file, including automatic filling of the project name, unit engineering name and preparation date, as well as the insertion of the cover image; The document generation module is used to output the final Word document for the to-be-generated solution file with completed cover information.
Citation Information
Patent Citations
Construction organization design intelligent compilation method and system
CN118798151A
Intelligent auxiliary generation method for power grid project review opinions based on information extraction
CN119721021A