작성
·
320
0
안녕하세요, 일코님.
엑셀 파일의 각 시트의 데이터를 읽어와서,
한글 보고서에 표로 넣는 자동화를 해보려고 시도 중입니다.
첫 번째 표는 잘 들어가는데,
두 번째 표를 돌리면 계속 아래 오류가 나면서 진행이 안되네요.
x0x1x0.py", line 35, in Execute
return self._oleobj_.InvokeTypes(15001, LCID, 1, (11, 0), ((8, 1), (9, 1)),actname
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2147417851, '서버에서 예외 오류가 발생했습니다.', None, None)
Retrying in 5 seconds...
Creating table with rows: 4 and columns: 4
Error inserting table (attempt 3): (-2147417851, '서버에서 예외 오류가 발생했습니다.', None, None)
Error type: <class 'pywintypes.com_error'>
Error args: (-2147417851, '서버에서 예외 오류가 발생했습니다.', None, None)
Traceback:
Traceback (most recent call last):
File "c:\StartCoding\직부캠결과보고서자동화.py\직부캠결과보고서.py", line 33, in insert_table_in_hwp
hwp.HAction.Execute("TableCreate", hwp.HParameterSet.HTableCreation.HSet)
File "C:\Users\김유빈\AppData\Local\Temp\gen_py\3.12\7D2B6F3C-1D95-4E0C-BF5A-5EE564186FBCx0x1x0.py", line 35, in Execute
return self._oleobj_.InvokeTypes(15001, LCID, 1, (11, 0), ((8, 1), (9, 1)),actname
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2147417851, '서버에서 예외 오류가 발생했습니다.', None, None)
코드를 GPT로 수정해보면,
첫 번째 표의 마지막 셀에 두 번째 표의 모든 내용이 붙는 것은 가능한데,
첫 번째 표를 만들고 그 닫음에 새로운 줄에서 두 번째 표가 붙는 게 계속 안됩니다.
혹시, 해당 문제를 해결할 수 있는 방법이 있을까요?ㅠㅠ
아래 내용은 제가 사용한 전체 코드입니다.
import os
import pandas as pd
import win32com.client as win32
import time
import traceback
def get_latest_download():
downloads_path = os.path.join(os.path.expanduser('~'), 'Downloads')
files = [os.path.join(downloads_path, f) for f in os.listdir(downloads_path) if f.endswith('.xlsx') or f.endswith('.xls')]
latest_file = max(files, key=os.path.getctime)
return latest_file
def read_excel_data(file_path):
if file_path.endswith('.xlsx'):
xl = pd.ExcelFile(file_path, engine='openpyxl')
elif file_path.endswith('.xls'):
xl = pd.ExcelFile(file_path, engine='xlrd')
else:
raise ValueError("지원되지 않는 파일 형식입니다. .xls 또는 .xlsx 파일을 사용해주세요.")
return xl
def clean_data(data):
return data.astype(str).apply(lambda x: x.str[:1000])
def insert_table_in_hwp(hwp, data, max_retries=3):
for attempt in range(max_retries):
try:
rows, cols = data.shape
print(f"Creating table with rows: {rows} and columns: {cols}")
hwp.HAction.GetDefault("TableCreate", hwp.HParameterSet.HTableCreation.HSet)
hwp.HParameterSet.HTableCreation.Rows = rows
hwp.HParameterSet.HTableCreation.Cols = cols
hwp.HAction.Execute("TableCreate", hwp.HParameterSet.HTableCreation.HSet)
for i in range(rows):
for j in range(cols):
if i != 0 or j != 0:
hwp.Run("MoveRight")
cell_value = str(data.iloc[i, j])
hwp.HAction.GetDefault("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HParameterSet.HInsertText.Text = cell_value
hwp.HAction.Execute("InsertText", hwp.HParameterSet.HInsertText.HSet)
print("Table inserted successfully.")
return
except Exception as e:
print(f"Error inserting table (attempt {attempt + 1}): {e}")
print(f"Error type: {type(e)}")
print(f"Error args: {e.args}")
print("Traceback:")
traceback.print_exc()
if attempt < max_retries - 1:
print(f"Retrying in 5 seconds...")
time.sleep(5)
else:
print("Max retries reached. Moving to next sheet.")
def move_cursor_outside_table(hwp):
# Move the cursor outside the table
hwp.HAction.Run("MoveDown") # Move down to make sure cursor is out of the table
hwp.HAction.Run("BreakPara") # Add a new paragraph break to ensure separation
hwp.HAction.Run("MoveDown") # Move down again
hwp.HAction.Run("BreakPara") # Add another paragraph break to ensure clear separation
def write_to_hwp(xl, hwp_file, output_file):
hwp = win32.Dispatch("HWPFrame.HwpObject")
hwp.RegisterModule("FilePathCheckDLL", "AutomationModule")
hwp.Open(hwp_file, "HWP", "forceopen:true")
# "표1" 누름틀 찾기
hwp.HAction.GetDefault("AllReplace", hwp.HParameterSet.HFindReplace.HSet)
hwp.HParameterSet.HFindReplace.FindString = "표1"
hwp.HParameterSet.HFindReplace.ReplaceString = "표1"
hwp.HParameterSet.HFindReplace.IgnoreMessage = 1
hwp.HAction.Execute("AllReplace", hwp.HParameterSet.HFindReplace.HSet)
# 누름틀 위치로 이동 및 내용 삭제
hwp.Run("Select")
hwp.Run("Delete")
for idx, sheet_name in enumerate(xl.sheet_names):
try:
print(f"Processing sheet: {sheet_name}")
data = clean_data(xl.parse(sheet_name, header=None))
print(f"Data from sheet {sheet_name}:\n{data}")
if idx > 0:
# 두 번째 시트부터는 줄바꿈 추가
hwp.HAction.GetDefault("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HParameterSet.HInsertText.Text = "\r\n\r\n"
hwp.HAction.Execute("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HAction.GetDefault("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HParameterSet.HInsertText.Text = sheet_name
hwp.HAction.Execute("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HAction.GetDefault("InsertText", hwp.HParameterSet.HInsertText.HSet)
hwp.HParameterSet.HInsertText.Text = "\r\n"
hwp.HAction.Execute("InsertText", hwp.HParameterSet.HInsertText.HSet)
time.sleep(2)
insert_table_in_hwp(hwp, data)
move_cursor_outside_table(hwp)
hwp.Run("BreakPara")
hwp.Run("BreakPara")
time.sleep(3)
except Exception as e:
print(f"Error processing sheet {sheet_name}: {e}")
print("Traceback:")
traceback.print_exc()
hwp.SaveAs(output_file, "HWP")
hwp.Quit()
if __name__ == "__main__":
latest_file = get_latest_download()
xl = read_excel_data(latest_file)
hwp_file_path = os.path.join(os.path.expanduser('~'), 'Desktop', '교육결과보고서.hwp')
output_file_path = os.path.join(os.path.expanduser('~'), 'Desktop', '교육결과보고서(자동화).hwp')
write_to_hwp(xl, hwp_file_path, output_file_path)
답변 1
0
안녕하세요, 인프런 AI 인턴입니다.
여러분의 문의는 프로그래밍 관련 질문이며, 특히 Python을 사용한 한글 문서(HWP) 자동화 처리 중 발생한 오류에 대한 것으로 보입니다. 주어진 코드 및 오류 메시지를 기반으로 몇 가지 해결 방안을 제안드립니다.
COM 오류 처리: 발생한 -2147417851, '서버에서 예외 오류가 발생했습니다.'
오류는 COM 서버(여기서는 한글 HWP 처리를 위한 COM 객체)와의 통신 중 예기치 않은 예외가 발생했음을 의미합니다. 이는 종종 HWP의 내부 상태나 외부 프로세스 간의 충돌로 인해 일어날 수 있습니다.
문제 해결을 위한 접근 방법:
move_cursor_outside_table
함수를 조정하거나, 필요한 경우 추가 로직을 구현해 보십시오.추가적인 디버깅:
Python과 win32com 라이브러리를 사용한 HWP 파일 자동화는 복잡하며, 때로는 예상치 못한 오류에 직면할 수 있습니다. 따라서, 상세한 로그를 통한 문제의 정확한 위치 파악과 함께 점진적인 디버깅을 시도해 보시기 바랍니다.