Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

메모장

Excel 파일 생성하기 본문

Delphi

Excel 파일 생성하기

우유한잔하죠 2016. 1. 20. 17:49

간단하게 로그를 저장하기 위해서 엑셀파일을 이용하기 위해서 알아낸 방법이다.

txt파일로 하면 파일크기나 접근성 부분에서 훨씬 용이하겠지만 공부의 한 방편으로 엑셀로 해 보았다.

모든 파일 종류(*.xls, *.xlsx 등등 많은 확장자가 존재. 엑셀 버전에 따라 생겨난 듯. 자세한 설명은 생략)를 다 해보진 않았고 *.xls, *.xlsx만 해보았다. 다른 확장자에 대한 답은 줄 수 없음.


코드

(SaveAs함수에 '('하나 빠진거 넣을 수 있도록)

uses절에 ComObj 추가.(이것 외에도 더 추가해야 할 수도 있음.)

procedure CreateExcelFile;
var
  vHandle : THandle;
  ExcelApp: OleVariant;
  ExcelBook: OleVariant;
  ExcelSheet: OleVariant;

  i : integer;
begin

  vHandle := FindWindow('XLMAIN', nil);
  vHandle := 0;
  if vHandle <> 0 then ExcelApp := GetActiveOleObject('Excel.Application')
  else begin
    try
      ExcelApp := CreateOLEObject('Excel.Application');
    except
      Application.MessageBox('Excel을 실행할 수 없습니다.'+ char(13) +
                             'Excel이 설치되어 있는지 확인하세요!',
                             '실행실패', MB_OK);
      exit;
    end;
  end;

  ExcelApp.DisplayAlerts := False; //메시지 표시 않기
  //ExcelApp.Visible := True; //엑셀보이기

  SetForegroundWindow(vHandle);

  // 워크북 추가
  ExcelApp.WorkBooks.Add;
  ExcelBook := ExcelApp.ActiveWorkBook;

  try
    // 작업할  워크시트 선택
    ExcelSheet := ExcelBook.WorkSheets[1];

    // 셀에 데이터 입력 예시(원하는 값 넣으면 됨.)
	ExcelSheet.Cells[1,1].Value := '1';
    ExcelSheet.Cells[1,2].Value := '2';
    ExcelSheet.Cells[1,3].Value := '3';
    ExcelSheet.Cells[1,4].Value := '4';
    ExcelSheet.Cells[1,5].Value := '5';

    // 워크북 저장
    ExcelBook.SaveAs('c:\ExcelOutputTest.xlsx');

  finally
    // 워크북 닫기
    ExcelBook.Close;
    ExcelBook := unAssigned;
    ExcelSheet := unAssigned;

    // 엑셀 종료
    ExcelApp.Quit;
    ExcelApp := unAssigned;
  end;
end;
Comments