Visual LISP, AutoLISP and General Customization
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Copy values from Excel to Lookup table single move

24 REPLIES 24
Reply
Message 1 of 25
nuno.ramos5SJR2
1694 Views, 24 Replies

Copy values from Excel to Lookup table single move

Hello everybody
It is with pleasure that I post this special request in this forum, and I hope that you can help in this matter that surely has already come up to someone.
Copying values from Excel to a Lookup table in AUTOCAD, in a single movement, is something I've been looking for for a long time. I recently discovered two almost perfect LISP routines that allow you to copy Excel to Lookup and vice versa in a single move. The problem is that it only works with Excel 2003 (no longer supported by Microsoft) and Autocad 2010.
I share with you the routines (comments in Russian) and ask if anyone can rewrite them so that they work in the latest versions of Excel and Autocad 2021 and above. I've tested it in Autocad 2021 and I guarantee it doesn't work.
If anyone manages to successfully rewrite the LISP routines, please share, they will surely be a lifeline for many CAD users.
Thank you very much and I pray that someone succeeds.

Labels (1)
24 REPLIES 24
Message 21 of 25

Good morning to all

To close this subject, my advice to all, is to install a virtual machine in your PC with Autocad 2007. The routines that I shared work just fine with 2007 version. It saves tones of time building the tables in EXCEL and then run EXCEL-LOOKUP.LSP to copy it to LOOKUP parameter in Autocad in a single step. 

Nevertheless lets make some pressure so that Autodesk includes this feature in the next versions of Autocad.

It was a pleasure to share with you my not so good experience with this Autodesk problem.

Message 22 of 25
scooberu
in reply to: nuno.ramos5SJR2


@nuno.ramos5SJR2 wrote:

Hi Sea-Haven

We also link Excel tables to dynamic properties of the block, using link tools of Autocad. 


Please share how you do this. 

Also, I am following this thread with interest.

Message 23 of 25
Sea-Haven
in reply to: scooberu

The Excel has to have the macros / formulas set up so when you put a value into say a excel cell it is checked within Excel, an example is a length and width must be say a min size else Excel puts a No in a cell , Acad reads the cell and looks at it is it Yes or No. Its no fancy lookups or anything all the work is done in Excel.

Message 24 of 25

I asked chatgtp to automate it for me. for me this solution worked.

If you need help to implement it feel free to ask!

 

Answer from ChatGPT:

 

Certainly! Below is a Python script that accomplishes the task you've described. This script listens for the Ctrl + D hotkey, retrieves the copied Excel table from the clipboard, and types it into AutoCAD's "Property Lookup Table" using simulated keyboard inputs. It also allows you to interrupt the typing process by pressing the Esc key.

Prerequisites

  1. Python Installation: Ensure you have Python 3.x installed on your system. You can download it from python.org.

  2. Required Python Libraries: You'll need to install the following Python libraries:

    • keyboard: To listen for and simulate keyboard events.
    • pyperclip: To access the clipboard.
    • pandas: To parse the Excel data.

    You can install these libraries using pip. Open your command prompt or terminal and run:

    bash
     
    pip install keyboard pyperclip pandas

    Note: On some systems, especially Windows, you might need to run the command prompt as an administrator to install these packages.

  3. Running the Script with Administrator Privileges: For the keyboard library to function correctly (especially on Windows), you might need to run the script with administrator rights.

The Python Script

import pyautogui
import keyboard
import pandas as pd
import pyperclip
import time
import sys

def on_hotkey_triggered():
    try:
        print("Ctrl + D detected. Processing clipboard data...")
       
        # Small delay to allow any UI changes to settle
        time.sleep(0.5)
       
        # Get clipboard content
        clipboard_data = pyperclip.paste()
       
        if not clipboard_data:
            print("Clipboard is empty. Please copy the Excel table first.")
            return
       
        # Attempt to read the clipboard as a DataFrame
        try:
            df = pd.read_clipboard(sep=None)  # Let pandas infer the separator
        except Exception as e:
            print("Failed to parse clipboard data as a table. Ensure it's copied from Excel.")
            print(f"Error: {e}")
            return
       
        if df.empty:
            print("The clipboard does not contain any data.")
            return
       
        print(f"Table detected with {len(df)} rows and {len(df.columns)} columns.")
       
        # Iterate through each cell in row-major order
        for row_idx, row in df.iterrows():
            for col_idx, cell in enumerate(row😞
                cell_text = str(cell)
               
                # Type the cell content
                pyautogui.typewrite(cell_text, interval=0.05)  # Adjust interval as needed
               
                # Press Tab to move to the next cell
                pyautogui.press('tab')
               
                # Optional: You can add a small delay if needed
                # time.sleep(0.01)
       
        print("Table input completed successfully.")
       
    except Exception as e:
        print("An unexpected error occurred:")
        print(e)

def main():
    print("AutoCAD Property Lookup Table Automation Script")
    print("Press Ctrl + D to paste the clipboard table into AutoCAD.")
    print("Press Esc to exit.")
   
    # Register the hotkey Ctrl + D
    keyboard.add_hotkey('ctrl+d', on_hotkey_triggered)
   
    # Wait until the user decides to exit
    keyboard.wait('esc')
    print("Exiting the script.")
    sys.exit()

if __name__ == "__main__":
    main()
 

How It Works

  1. Hotkey Registration:

    • Ctrl + D: Triggers the on_ctrl_d function, which reads the clipboard, parses the table, and starts typing.
    • Esc: Triggers the on_esc function, which sets the typing flag to False, effectively stopping the typing process.
  2. Clipboard Parsing:

    • The script uses pyperclip to access the clipboard content.
    • It then uses pandas to parse the clipboard data assuming it's tab-delimited (which is typical when copying from Excel).
  3. Typing Mechanism:

    • The type_table function iterates over each row of the DataFrame.
    • It simulates typing each cell's content, separated by tabs (\t), and sends a Tab key press after each row to move to the next row in AutoCAD.
    • The typing is done in a separate thread to allow real-time interruption via the Esc key.
  4. Interruption Handling:

    • Pressing Esc sets the typing flag to False, which breaks the typing loop and stops any further typing.

Usage Instructions

  1. Prepare Your Excel Table:

    • Ensure that the table in Excel matches the structure expected by AutoCAD's "Property Lookup Table".
    • Select the entire table and copy it to the clipboard (Ctrl + C).
  2. Run the Script:

    • Save the provided script to a file, e.g., autocad_paste.py.

    • Open a command prompt or terminal with administrator privileges.

    • Navigate to the directory containing the script.

  3. Paste into AutoCAD:

    • Switch to AutoCAD and select the first cell in the "Property Lookup Table".
    • Press Ctrl + D to start the automated typing process.
    • The script will type out the entire table, navigating through rows and columns using Tab.
  4. Interrupt if Needed:

    • If you need to stop the typing process for any reason, press the Esc key.

Additional Notes

  • Adjusting Typing Speed: If the typing is too fast or too slow for AutoCAD to handle, you can adjust the delay parameter in the keyboard.write function and the time.sleep duration between rows.

  • Error Handling: The script includes basic error handling to notify you if the clipboard is empty or if there's an issue parsing the clipboard data.

  • Compatibility: This script is primarily designed for Windows due to the nature of the keyboard library. If you're using a different operating system, you might need to use alternative libraries or methods.

  • Safety: Be cautious when running scripts that control keyboard input. Ensure that the target application (AutoCAD) is in focus and that you don't have any unintended active inputs that could be disrupted.

Troubleshooting

  • Script Not Responding to Hotkeys:

    • Ensure you're running the script with the necessary permissions (administrator).
    • Verify that no other application is capturing the Ctrl + D or Esc hotkeys.
  • Clipboard Parsing Issues:

    • Ensure that the copied Excel table is properly formatted and that it's being copied as a tab-delimited table.
    • If your data uses a different delimiter, adjust the delimiter parameter in the pd.read_csv function accordingly.
  • Typing Interruptions:

    • If pressing Esc doesn't stop the typing, ensure that the script is actively listening for the Esc key and that no other application is interfering with keyboard events.

Conclusion

This script should help bridge the gap between Excel and AutoCAD by automating the process of transferring data from a clipboard to a "Property Lookup Table" in AutoCAD. Customize and adjust the script as needed to better fit your specific workflow and requirements.

If you encounter any issues or have further questions, feel free to ask!

Message 25 of 25
Sea-Haven
in reply to: nuno.ramos5SJR2

No need for copy and paste type method if you can read a Excel cell then you can take that value and apply it to a dynamic block property, that includes visibility states. 

 

I would suggest you look at Lee-mac.com dynamic block properties lisp, it has several functions that allow for the manipulation of dynamic block properties. Big hint python version, definitely no paste.

 

I am not sure that maybe the words "Look up table" is correct maybe I am just reading the last couple of post all wrong.

 

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

AutoCAD Inside the Factory


Autodesk Design & Make Report