엑셀에서 이미지와 텍스트 데이터를 행별로 추출하는 작업이네요. 두 가지 효과적인 방법을 제안드리겠습니다.
방법 1: Python 사용 (추천)
import openpyxl
from openpyxl_image_loader import SheetImageLoader
import pandas as pd
import os
from PIL import Image
def extract_excel_data_with_images(file_path, output_folder):
# 엑셀 파일 열기
wb = openpyxl.load_workbook(file_path)
ws = wb.active
# 이미지 로더 초기화
image_loader = SheetImageLoader(ws)
# 출력 폴더 생성
os.makedirs(output_folder, exist_ok=True)
extracted_data = []
# 데이터가 있는 행 범위 확인
max_row = ws.max_row
for row in range(2, max_row + 1): # 1행은 헤더라고 가정
row_data = {
'row_number': row,
'A_column': ws[f'A{row}'].value,
'B_column': ws[f'B{row}'].value,
'C_column': ws[f'C{row}'].value,
'Q_column': ws[f'Q{row}'].value,
'R_column': ws[f'R{row}'].value,
'S_column': ws[f'S{row}'].value,
'images': []
}
# P열의 이미지 추출
cell_address = f'P{row}'
if image_loader.image_in(cell_address):
try:
image = image_loader.get(cell_address)
image_filename = f'row_{row}_image.png'
image_path = os.path.join(output_folder, image_filename)
image.save(image_path)
row_data['images'].append(image_filename)
except Exception as e:
print(f"행 {row}의 이미지 처리 중 오류: {e}")
extracted_data.append(row_data)
# 데이터를 DataFrame으로 변환하여 CSV로 저장
df = pd.DataFrame(extracted_data)
df.to_csv(os.path.join(output_folder, 'extracted_data.csv'), index=False, encoding='utf-8-sig')
return extracted_data
# 사용법
file_path = "your_excel_file.xlsx"
output_folder = "extracted_data"
result = extract_excel_data_with_images(file_path, output_folder)
필요한 라이브러리 설치:
pip install openpyxl openpyxl-image-loader pandas pillow
방법 2: VBA 매크로
Sub ExtractDataWithImages()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim outputPath As String
Dim fso As Object
Dim textFile As Object
Set ws = ActiveSheet
Set fso = CreateObject("Scripting.FileSystemObject")
' 출력 폴더 설정
outputPath = ThisWorkbook.Path & "\ExtractedData\"
If Not fso.FolderExists(outputPath) Then
fso.CreateFolder outputPath
End If
' 텍스트 데이터를 저장할 CSV 파일 생성
Set textFile = fso.CreateTextFile(outputPath & "extracted_data.csv", True)
textFile.WriteLine "Row,A_Column,B_Column,C_Column,Q_Column,R_Column,S_Column,Image_Count"
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow ' 2행부터 시작 (1행은 헤더라고 가정)
' 텍스트 데이터 추출
Dim rowData As String
rowData = i & "," & _
Replace(ws.Cells(i, 1).Value, ",", ";") & "," & _
Replace(ws.Cells(i, 2).Value, ",", ";") & "," & _
Replace(ws.Cells(i, 3).Value, ",", ";") & "," & _
Replace(ws.Cells(i, 17).Value, ",", ";") & "," & _
Replace(ws.Cells(i, 18).Value, ",", ";") & "," & _
Replace(ws.Cells(i, 19).Value, ",", ";")
' P열의 이미지 처리
Dim imageCount As Integer
imageCount = 0
Dim shp As Shape
For Each shp In ws.Shapes
If shp.Type = msoPicture Then
If IsImageInCell(shp, ws.Cells(i, 16)) Then
imageCount = imageCount + 1
Call ExportImage(shp, outputPath & "row_" & i & "_image_" & imageCount & ".png")
End If
End If
Next shp
rowData = rowData & "," & imageCount
textFile.WriteLine rowData
Next i
textFile.Close
MsgBox "데이터 추출이 완료되었습니다. 경로: " & outputPath
End Sub
Function IsImageInCell(shp As Shape, cell As Range) As Boolean
IsImageInCell = (shp.TopLeftCell.Address = cell.Address)
End Function
Sub ExportImage(shp As Shape, fileName As String)
On Error Resume Next
shp.Copy
Dim chart As ChartObject
Set chart = ActiveSheet.ChartObjects.Add(0, 0, shp.Width, shp.Height)
chart.Activate
ActiveChart.Paste
ActiveChart.Export fileName
chart.Delete
End Sub
방법 3: xlwings 사용 (Python + Excel 연동)
import xlwings as xw
import os
import pandas as pd
def extract_with_xlwings(file_path, output_folder):
app = xw.App(visible=False)
wb = app.books.open(file_path)
ws = wb.sheets[0]
os.makedirs(output_folder, exist_ok=True)
# 데이터 범위 확인
last_row = ws.range('A1').end('down').row
extracted_data = []
for row in range(2, last_row + 1):
row_data = {
'row_number': row,
'A_column': ws.range(f'A{row}').value,
'B_column': ws.range(f'B{row}').value,
'C_column': ws.range(f'C{row}').value,
'Q_column': ws.range(f'Q{row}').value,
'R_column': ws.range(f'R{row}').value,
'S_column': ws.range(f'S{row}').value,
}
# 이미지 처리는 xlwings의 pictures 속성 사용
# (구체적인 구현은 엑셀 파일 구조에 따라 조정 필요)
extracted_data.append(row_data)
wb.close()
app.quit()
# CSV로 저장
df = pd.DataFrame(extracted_data)
df.to_csv(os.path.join(output_folder, 'extracted_data.csv'), index=False, encoding='utf-8-sig')
return extracted_data
추천사항
Python 방법 1을 추천합니다. 이유는:
- 이미지 처리가 안정적
- 대용량 데이터 처리에 유리
- 결과물을 다양한 형태로 가공 가능
- 자동화하기 쉬움
엑셀 파일의 구체적인 구조나 이미지 배치 방식에 따라 코드를 약간 조정해야 할 수 있으니, 실제 파일로 테스트해보시고 필요시 세부 조정을 요청해 주세요.