최대값 구하는 알고리즘


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
            using System;
 
              public class 최대값
              {
                  public static void Main()
                  {

                      
                      int[] data = { 16924, 18 };
                      int max = data[0];
                            
//여기가 최대값 구하는 알고리즘
                      for (int i = 0; i < data.Length; i++)
                      { 
                          if(max < data[i])
                          {
                              max = data[i];
                          }
                      }
 
                              
                      Console.WriteLine("최대값 : {0}", max); ;
                  }    
              }

//cs


'C#' 카테고리의 다른 글

C# using 쓰는 이유  (0) 2019.01.31
엑셀 다루기  (0) 2019.01.30
C# 최소값 구하기(알고리즘)  (0) 2019.01.30

winform 엑셀 저장(초고속) 클립보드 캡쳐방식입니다



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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
private void Export_Excel(string path) //savefildialog.filename
        {
            //xls는 65536, xlsx는 1048575
            dataGridView1.MultiSelect = true;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AllowUserToAddRows = false;
 
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
            {
                Clipboard.SetDataObject(dataObj);
            }
            Excel.Application xlexcel;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = Missing.Value;
            xlexcel = new Excel.Application();
            xlexcel.Visible = false;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[11];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.MultiSelect = false;
 
            if (path.Contains(".xlsx"))
            {
                xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookDefault, nullnullfalsefalse,
                Excel.XlSaveAsAccessMode.xlShared, falsefalsenullnullnull);
            }
            else
            {
                xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal, nullnullfalsefalse,
                Excel.XlSaveAsAccessMode.xlShared, falsefalsenullnullnull);
            }
 
            dataGridView1.ClearSelection();
            xlexcel.Quit();
 
            releaseObject(CR);
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlexcel);
            MessageBox.Show("저장완료");
        }
cs


'Winform' 카테고리의 다른 글

winform 각 행의 색표시  (0) 2019.01.30
winform 차트 예제  (0) 2019.01.30
winform 엑셀 죽이기 완벽한 방법  (0) 2019.01.29
winform DataGridView to Excel  (0) 2019.01.22
winform 엑셀 import  (0) 2019.01.17

winform 에서 엑셀 작업을 하고 프로세스를 지워주지 않으면 메모리를 계속 갉아 먹기에 컴퓨터가 느려진다


winform 에서 엑셀 작업을 한뒤에는 반드시 프로세스를 지워줘야 하는데  이 지우는 방법이 매우 어렵더라


구글링 해본 결과 엑셀작업을 할때 차례대로 열어놓은 엑샐 객체들을 차례대로 닫고 릴리즈 해줘야 한다는데 


적용이 힘들고 잘 되지 않을 뿐더러 무엇보다더 지저분해진다


나의 방법은 내가 winform 엑샐 작업시 열었던 그 엑셀의 프로세스 ID를 기억해 process.kill(프로세스ID) 해버리는 방법이다


이 방법의 좋은 점은 간편하고 쉬우며 직관성이 좋다.


아래에 코드를 소개 하겠으니 모두들 홧팅



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 프로세스 id 찾는
[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);
 
int GetExcelProcess(Excel.Application excelApp)
    {
        int id;
        GetWindowThreadProcessId(excelApp.Hwnd, out id);
            
        //return Process.GetProcessById(id); 리턴방식으로 써도 됨
        return id;
    }
 
 
// Excel 프로그램을 의미합니다.
Excel.Application excelApp = new Excel.Application();    
 
//엑셀 프로세스를 찾아서~
 Process p = Process.GetProcessById(GetExcelProcess(excelApp));
 
//죽이자
p.Kill();  
cs


'Winform' 카테고리의 다른 글

winform 차트 예제  (0) 2019.01.30
winform 엑셀 저장(초고속)  (0) 2019.01.29
winform DataGridView to Excel  (0) 2019.01.22
winform 엑셀 import  (0) 2019.01.17
winform cursor waiting 마우스 로딩  (0) 2019.01.17

이 방법은 클립보드 형식이라서 매우 빠릅니다


https://stackoverflow.com/questions/18182029/how-to-export-datagridview-data-instantly-to-excel-on-button-click




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
//쓰기
        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AllowUserToAddRows = false;
 
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
            {
                Clipboard.SetDataObject(dataObj);
            }
            Excel.Application xlexcel;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = Missing.Value;
            xlexcel = new Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[11];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
 
        }
cs





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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// 엑셀 가져오기 함수
        private void importExcel()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "엑셀 파일 선택하세요";
            openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            DialogResult result = openFileDialog.ShowDialog();
 
            if (result == DialogResult.OK)
            {
 
                this.Cursor = Cursors.WaitCursor;
                //엑셀 앱
                Excel.Application app = new Excel.Application();
 
                Excel.Workbooks workbooks = app.Workbooks;
 
                //엑셀 워크북(파일경로읽어서)
                Excel.Workbook workbook = workbooks.Open(openFileDialog.FileName);
 
                // 엑셀 워크싯 객체
                Excel.Sheets sheets = workbook.Worksheets;
 
                Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
 
                
 
                // 엑셀파일 이름이 나온다
                string excelFileName = workbook.Name;
                
                //excelFileName = excelFileName.Substring(book.Name.Length-3);
                string[] str = excelFileName.Split('.');
 
                // 워크시트 첫번째 이름
                string workSheetName = worksheet.Name;
                
                try
                {
                    if (str[1].Equals("xls"))
                    {
                        // 연결 string
                        string constr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" 
+ openFileDialog.FileName + "';Extended Properties=Excel 8.0;";
 
                        //경로까지 다 포함해서 .xls라고 뜨네;
                        //MessageBox.Show(openFileDialog.FileName);
 
                        // excel conn
                        OleDbConnection conn = new OleDbConnection(constr);
 
                        // excel cmd
                        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
                        conn.Open();
 
                        OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        this.Cursor = Cursors.WaitCursor;
                        dataGridView1.DataSource = dt;
                        this.Cursor = Cursors.Default;
                        conn.Close();
 
                        
                    }
                    else if (str[1].Equals("xlsx"))
                    {
                        // 연결 string
                        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        openFileDialog.FileName +
                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
 
                        //경로까지 다 포함해서 .xls라고 뜨네;
                        //MessageBox.Show(openFileDialog.FileName);
 
                        // excel conn
                        OleDbConnection conn = new OleDbConnection(constr);
 
                        // excel cmd
                        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
                        conn.Open();
 
                        OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        
                        dataGridView1.DataSource = dt;
                        this.Cursor = Cursors.Default;
                        conn.Close();
                       
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    //메모리                     
                    workbook.Close(Type.Missing, openFileDialog.FileName, Type.Missing);
                    app.Quit();
 
                    if(worksheet!=null) releaseObject(worksheet);
                    if (sheets != null) releaseObject(sheets);
                    if (workbook != null) releaseObject(workbook);
                    if (workbooks != null) releaseObject(workbooks);
                    if (app != null) releaseObject(app);
 
 
                }
            }
        }
 
        #region 메모리해제
        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception e)
            {
                obj = null;
                throw e;
            }
            //finally
            //{
            //    GC.Collect();
            //}
        }
        #endregion
cs



우리의 컴퓨터가 어떤 작업을 할때 마우스가 빙글빙글 돌아가는 모습을 본적 있으시죠?


winform 에서도 그렇게 할 수 있습니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
this.Cursor = Cursors.WaitCursor;   //Waitting
 
this.Cursor = Cursors.Default;   //원래대로
 
 
//둘다 같다 난 밑에걸 선호(위에건 폼안에서만 돈다고하네요)
 
 
Cursor.Current = Cursors.WaitCursor;   //Waitting
 
Cursor.Current = Cursors.Default;   //원래대로
 
 
 
 
cs


데이터 그리드 뷰의 유용한 기능들을 모았어요


1
2
3
4
5
6
7
8
9
10
11
12
13
14
            //행 전체 선택 할 수 있도록
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
 
            //맨 앞 열 삭제
            dataGridView1.RowHeadersVisible = false;
 
            // 그리드뷰 컬럼폭 채우기
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
 
            // 데이터 그리드 뷰 가득 채우기
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
 
            //마지막행 삭제
            dataGridView1.AllowUserToAddRows = false;
cs



'Winform' 카테고리의 다른 글

winform 엑셀 import  (0) 2019.01.17
winform cursor waiting 마우스 로딩  (0) 2019.01.17
winform property resources 추가  (0) 2019.01.15
winform SqlCommand  (0) 2019.01.15
winform SqlConnection  (0) 2019.01.15

winform 하다보면 프로퍼티에 사진을 추가하고 싶을때가 있습니다


한번 해볼까요?





이렇게 사용하실 수 있습니다! ㅎㅎ

+ Recent posts