2017년 3월 21일 화요일

엑셀 파일 데이타 강제로 담기

http://leemcse.tistory.com/entry/C-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%A8%EC%9C%BC%EB%A1%9C-Excel-File%EC%9D%84-%EB%B6%88%EB%9F%AC%EC%98%A4%EA%B8%B0
 
 
[ 1 ]
 
==> 추가 사항 . 
using System.Data.OleDb;
using Microsoft.Office.Interop;




[ 2 ]
== > 전역 변수 선언 ( MS- ExCel 버전 별로 코딩방식이 달라 두개의 변수 선언  1. Excel 97_2003, Excel 2007 용 ))
private const string ConnectStrFrm_Excel97_2003 =
     "Provider=Microsoft.Jet.OLEDB.4.0;" +
     "Data Source=\"{0}\";" +
     "Mode=ReadWrite|Share Deny None;" +
     "Extended Properties='Excel 8.0; HDR={1}; IMEX={2}';" +
     "Persist Security Info=False";
     // 확장명 XLSX (Excel 2007 이상용)
private const string ConnectStrFrm_Excel =
     "Provider=Microsoft.ACE.OLEDB.12.0;" +
     "Data Source=\"{0}\";" +
     "Mode=ReadWrite|Share Deny None;" +
     "Extended Properties='Excel 12.0; HDR={1}; IMEX={2}';" +
     "Persist Security Info=False";




[ 3 ]
--> 본문


string Source = string.Empty;
string ConnStr = string.Empty;
 try
 {
         System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C:\\AAA\\BBBBB\\Data"); < -- 특정경로 설정
         System.IO.FileInfo[] fi = di.GetFiles("검정백신정보*");                                                          <--  특정 문자로 시작하거 찾기
        
        if (fi.Length == 0)
        {
            MessageBox.Show("파일이없습니다.");
            return; 
         }
        else
            FileName = fi[0].Name.ToString();


            FileName = System.Windows.Forms.Application.StartupPath +"\\Data\\"+ FileName;

int ExcelType = ExcelFileType(FileName); <-- Excel 버전 변환 부분
       
        switch (ExcelType)
        {
            case (-2): throw new Exception(Source + "의 형식검사중 오류가 발생하였습니다.");
            case (-1): throw new Exception(Source + "은 엑셀 파일형식이 아닙니다.");
            case (0):
               ConnStr = string.Format(ConnectStrFrm_Excel97_2003, Source, "True", "1");
                 break;
           case (1):
               ConnStr = string.Format(ConnectStrFrm_Excel, Source, "True", "1");
                break;
         }

             OleDbConnection excelConn = null;
             string xlsfilename;
             DataTable excelTable = new DataTable();
             DataSet exceIDs = new DataSet();
             DataRow lastDr = null;
             excelTable.Columns.Add("SEQNO", typeof(string));
             excelTable.Columns.Add("LOTNO", typeof(string));
             excelTable.Columns.Add("VACODE", typeof(string));
             excelTable.Columns.Add("VENDORCODE", typeof(string));
             excelTable.Columns.Add("LOPPERID", typeof(string));
             excelTable.Columns.Add("VANAME", typeof(string));
             excelTable.Columns.Add("VENDORNAME", typeof(string));
              excelTable.Columns.Add("UNIT", typeof(string));
              excelTable.Columns.Add("VCNCOD", typeof(string));
              try
              {
                   
                    string strCon = ConnStr;
                    excelConn = new OleDbConnection(strCon);
                    excelConn.Open();
                    string excelSql = @"select * from [Sheet1$]";
                    OleDbDataAdapter excelAdapter = new OleDbDataAdapter(excelSql, excelConn);
                    excelAdapter.Fill(exceIDs);
                    excelTable = exceIDs.Tables[0];
                }
                catch (Exception ex)
                {
                    MessageBox.Show("파일 가져오기 실패 :" + ex.Message);
                }
                DataRow[] drs = excelTable.Select("SEQNO > '0'");
                DataSet ds = new DataSet();
                ds.Merge(drs);
                DataTable dt1 = null;
                if (ds.Tables.Count > 0)
                {
                    dt1 = ds.Tables[0].Copy();
                }
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    _controller.InsertVaccMstExcelData(dt1);
                    this.ShowInstanceMessage("HIS.MD", "제조번호 갱신이 완료되었습니다. ", 2);
                }
                else
                {
                    this.ShowInstanceMessage("HIS.MD", "갱신할 제조번호가 없습니다. ", 2);
                }              

            }
            catch (Exception ex)
            {
                if (ex.Message.StartsWith("제한 시간이 만료되었습니다.")
                    || ex.Message.StartsWith("Timeout이 만료되었습니다.")
                    || ex.Message.StartsWith("Timeout expired."))
                {
                    MessageBoxViewer.ShowAlert(this, "HIS.Common", "COMMON_DB_TIMEOUT");
                }
                else if (ex.Message.StartsWith("XX_") || ex.Message.StartsWith("MD"))
                {
                    MessageBoxViewer.ShowAlert(this, "HIS.MD", ex.Message);
                }
                else if (ex.Message.StartsWith("HP"))
                {
                    MessageBoxViewer.ShowAlert(this, "HIS.HP", ex.Message);
                }
                else
                {
                    MessageBoxViewer.ShowError(this, "HIS.MD", ex.Message, ex, "VaccPatMgtDF", "CodeDataLoad", "");
                }
            }

        }
        // 버전 체크 메서드
        public static int ExcelFileType(string XlsFile)
        {
            byte[,] ExcelHeader = {
                { 0xD0, 0xCF, 0x11, 0xE0, 0xA1 }, // XLS  File Header
                { 0x50, 0x4B, 0x03, 0x04, 0x14 }  // XLSX File Header
            };
            // result -2=error, -1=not excel , 0=xls , 1=xlsx
            int result = -1;
            FileInfo FI = new FileInfo(XlsFile);
            FileStream FS = FI.Open(FileMode.Open);
            try
            {
                byte[] FH = new byte[5];
                FS.Read(FH, 0, 5);
                for (int i = 0; i < 2; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        if (FH[j] != ExcelHeader[i, j]) break;
                        else if (j == 4) result = i;
                    }
                    if (result >= 0) break;
                }
            }
            catch
            {
                result = (-2);
                //throw e;
            }
            finally
            {
                FS.Close();
            }
            return result;
        }

Command 명령어를 이용한 내부네트워크 제어

Q) 옛날 도스 명령어를 C# 코드에 삽입하여 코딩함.
   --> 예제) 프로그램 로딩시 내부네트워크 제어


  private void ControlInsideNetWork()
        {
            ProcessStartInfo cmd = new ProcessStartInfo();
            Process process = new Process();
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            //var networks = NetworkInterface.GetAllNetworkInterfaces();
            cmd.FileName = @"cmd";
            cmd.CreateNoWindow = false;
            cmd.UseShellExecute = false;
            cmd.RedirectStandardOutput = true;
            cmd.RedirectStandardInput = true;
            cmd.RedirectStandardError = true;
            string adapter = string.Empty;
            IPHostEntry host;
            string localIP = string.Empty;
            host = Dns.GetHostEntry(Dns.GetHostName());
            //int count = 0;
            int RowCount = 0;
            //활성화 여부 체크
            foreach (NetworkInterface UseYn in nics)
            {
                if (UseYn.OperationalStatus.ToString().Trim() == "Up")
                {
                    RowCount++;
                }
            }
            //내부네트워크 체크
            for (int i = 0; i < host.AddressList.Length; i++)
            {
                //if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                //    count++;
                if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork &&
                    host.AddressList[i].ToString().Substring(0, 3) == "172")
                    localIP = LocalName;
            }
            //개수 체크
            if (RowCount > 2)
            {
                process.StartInfo = cmd;
                process.Start();
                // Command 명령어 삽입
                process.StandardInput.Write(@"netsh interface set interface name = " + "\"" + localIP + "\" admin= disabled" + Environment.NewLine);
                process.StandardInput.Close();
                string resultValue = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

        }
 ==> PC 안에 내부네트워크 셋팅함.
 private void DNSSetting()
        {
            ProcessStartInfo cmd = new ProcessStartInfo();
            Process process = new Process();
            cmd.FileName = @"cmd";
            cmd.CreateNoWindow = true;
            cmd.UseShellExecute = false;// false
            cmd.RedirectStandardOutput = true;
            cmd.RedirectStandardInput = true;
            cmd.RedirectStandardError = true;
           
            foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet && ni.Name.Contains("로컬"))
                {
                    LocalName = ni.Name;
                }
            }
           
            process.StartInfo = cmd;
            process.Start();
           
            process.StandardInput.Write(@"netsh interface ipv4 set dns name = " + "\"" + LocalName + "\" static 172.31.7.30 " + Environment.NewLine);
            process.StandardInput.Write(@"netsh interface ipv4 add dns name = " + "\"" + LocalName + "\" 172.31.11.30 index=2 " + Environment.NewLine);
            process.StandardInput.Write(@"netsh interface ipv4 set wins name = " + "\"" + LocalName + "\" static 172.31.11.30 " + Environment.NewLine);
            process.StandardInput.Write(@"netsh interface ipv4 add wins name = " + "\"" + LocalName + "\" 172.31.7.30 index=2 " + Environment.NewLine);
           
           
            process.StandardInput.Close();
            string resultValue = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            process.Close();



        }


[C#] 스프레드 Sheet Copy

참고 : http://blog.daum.net/lsj8601/44
 
ex ) ---> 스프레드 Sheet 1, 2,3  데이타 각각 가져와서 Excel에 뿌려주기 

            FarPoint.Win.Spread.SheetView sv = new FarPoint.Win.Spread.SheetView();
            FarPoint.Win.Spread.SheetView sv01 = new FarPoint.Win.Spread.SheetView();
            FarPoint.Win.Spread.SheetView sv02 = new FarPoint.Win.Spread.SheetView();
          --> 스프레드 데이타 복사 
            sv   = CopySheet(this.spdNICUFollowDetailList.ActiveSheet);
            sv01 = CopySheet(this.spdNICUDetail01.ActiveSheet);
            sv02 = CopySheet(this.spdNICUDetail02.ActiveSheet);

            SaveFileDialog saveExcelFileDialog = new SaveFileDialog();
            saveExcelFileDialog.InitialDirectory = "C:\\";
            saveExcelFileDialog.Filter = "Excel files (*.xls)|*.xls";
            saveExcelFileDialog.FilterIndex = 0;
            saveExcelFileDialog.FileName = "NICU_" + this.txtUnitNo.Text; //+ "_" + this.txtPatNm.Text;

            if (saveExcelFileDialog.ShowDialog() == DialogResult.OK)
            {

                this.fpspreadExc.Sheets[0].Protect = false;
                this.fpspreadExc.Sheets[1].Protect = false;
                this.fpspreadExc.Sheets[2].Protect = false;
                
                // 하나의 스프레드를 만들어서 Sheet 별로 담기 
                fpspreadExc.Sheets[0] = sv;
                fpspreadExc.Sheets[1] = sv01;
                fpspreadExc.Sheets[2] = sv02;
                this.fpspreadExc.Visible = true;
                
                // 담은 값을 엑셀에 뿌려주기 
                this.fpspreadExc.SaveExcel(saveExcelFileDialog.FileName,     FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);

                this.fpspreadExc.Visible = false;
                this.fpspreadExc.Sheets[0].Protect = true;
                this.fpspreadExc.Sheets[1].Protect = true;
                this.fpspreadExc.Sheets[2].Protect = true;
            
                MessageBoxViewer.ShowAlert("HIS.SP", "SET_SAVE_SUCCEEDED");
                
               
                
            }
--> 스프레드 Copy 사용자메서드 
public FarPoint.Win.Spread.SheetView CopySheet(FarPoint.Win.Spread.SheetView sheet)
        {
            FarPoint.Win.Spread.SheetView newSheet = null;
            if (sheet != null)
            {
                newSheet = (FarPoint.Win.Spread.SheetView)FarPoint.Win.Serializer.LoadObjectXml(sheet.GetType(),                     FarPoint.Win.Serializer.GetObjectXml(sheet, "CopySheet"), "CopySheet");
            }
            return newSheet;
        } 

엑셀 파일 데이타 강제로 담기

http://leemcse.tistory.com/entry/C-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%A8%EC%9C%BC%EB%A1%9C-Excel-File%EC%9D%84-%EB%B6%88%EB%9F%AC%EC%98%A4%EA...