2012-06-25

C# 배열의 내용을 Excel sheet에 채우기


 
/// 
/// Excel
/// .Application 액셀 어플리케이션 자체
/// ._Workbook 워크북 = 엑셀 파일
/// .Sheets 엑셀 시트의 배열
/// ._Worksheet 액티브된 단일 시트
/// .Range 편집범위
/// 
using System;
using System.Text;
using Excel=Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Diagnostics;
namespace automating_system_report
{
    class ExcelUpdater:FileManager
    {


        #region const var
        #endregion const var

        #region public global var
        public Excel.Application objApp = new Excel.Application();
        public Excel._Workbook objBook;
        #endregion public global var
        
        #region 생성자&소멸자
        public ExcelUpdater() //기본 생성자
        { }
        public ExcelUpdater(string sourcefile, string targetfile)//템플릿 파일과 생성할 파일을 파라미터로 주고 open
        {
            LoadFile(sourcefile,targetfile);
        }
        ~ExcelUpdater()
        {
            //PRB: Visual Studio .NET 클라이언트에서 자동화 후에 Office 응용 프로그램이 종료되지 않는다(http://support.microsoft.com/kb/317109)
            UnLoadFile();
        }
        #endregion 생성자&소멸자

        #region public Method
        /// 
        /// updateSheet, 배열의 내용으로 sheet를 채운다.
        /// 줄과 칸을 각각 받았으나 "A1" 형식의 위치를 받기로 변경함.
        /// 
        /// 데이터를 붙여넣을 sheet번호. 1부터 시작
        /// 붙여넣기 시작할 위치, (예: "A1")
        /// 붙여넣을 내용, 문자열 2차원 배열
        public bool updateSheet(int sheetNumber, string writeStartLoc, ref string[,] rawdata)
        {
            try
            {
                Excel.Sheets objSheets = objBook.Sheets;
                Excel._Worksheet objSheet = objSheets[sheetNumber];
                Excel.Range range;
                range = objSheet.get_Range(writeStartLoc);
                range = range.get_Resize(rawdata.GetLength(0), rawdata.GetLength(1));
                range.set_Value(null, rawdata);
                return true;
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }
        /// col과 row로 호출하면, "A1"형식으로 변환.
        /// 데이터를 붙여넣을 sheet번호. 1부터 시작
        /// 붙여넣기 시작할 줄, 1부터 시작
        /// 붙여넣기 시작할 칸, 0부터 시작(0~16383)
        /// 붙여넣을 내용, 문자열 2차원 배열
        public void updateSheet(int sheetNumber,int writeStartRow,int writeStartCol,ref string[,] rawdata)
        {
            // Row와 Col을 저장할 변수들
            string writeStartLoc;
            writeStartLoc = DecToAlphabet(writeStartCol) + writeStartRow.ToString(); // row 1, col 0일 경우 loc은 "A1"
            updateSheet(sheetNumber, writeStartLoc, ref rawdata);
        }
        public bool LoadFile(string TemplateXlsFile, string CopiedXlsFile) // source파일의 사본을 만들고 로드
        {
            FullPath = CopiedXlsFile;

            try // 엑셀파일이 열려있을 경우 오류
            {
                //System.IO.File.Delete(FullPath);
                System.IO.File.Copy(TemplateXlsFile, CopiedXlsFile, true); //템플릿을 복사
                objBook = objApp.Workbooks.Open(CopiedXlsFile);
                //  objApp.Visible = true; // Excel app의 visible=false;

                return true;
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }
        public void UnLoadFile() // 엑셀 프로세스를 저장없이 그냥 닫을 때 사용.
        {
            objBook = null;
            objApp = null;
        }
        public bool CloseAndSave() // 엑셀 파일 저장.
        {
            try
            {
                objBook.Save();
                objBook.Close();
                objApp.Quit();  //프로세스에서 삭제
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

     
        /// 
        /// 10진수 컬럼 값을 엑셀에서 사용하는 컬럼 값 처럼, 알파벳으로 변환
        /// 
        /// 0은 A, Z는 25
        /// 
        public string DecToAlphabet(int num)
        {
            int rest; //나눗셈 계산에 사용될 나머지 값
            string alphabet; //10진수에서 알파벳으로 변환될 값

            byte[] asciiA = Encoding.ASCII.GetBytes("A"); // 0=>A
            rest = num % 26; // A~Z 26자
            asciiA[0] += (byte)rest; // num 0일 때 A, num 4일 때 A+4 => E

            alphabet = Encoding.ASCII.GetString(asciiA); //변환된 알파벳 저장
            
            num = num / 26 -1; // 그 다음 자리의 알파벳 계산을 재귀하기 위해, 받은 수/알파벳수 -1 (0은 A라는 문자값이 있으므로 -1을 기준으로 계산함)
            if (num > -1) 
            {
                alphabet = alphabet.Insert(0, DecToAlphabet(num)); //재귀 호출하며 결과를 앞자리에 insert
            }
            return alphabet; // 최종값 return
        }
        /// int input=Int32.Parse(textBox1.Text.ToString());
        /// Trace.WriteLine(input+"=> "+ xlsmaker.DecToAlphabet(input));
        /// 결과
        /// 0=> A
        /// 27=> AB
        /// 16383=> XFD
        #endregion public Method
    }
}
//


댓글 없음:

댓글 쓰기