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 | private void btnExcelDownload_Click(object sender, EventArgs e) { if (grid1.Rows.Count <= 0) return; Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; Excel.Range oRng; try { oXL = new Excel.Application(); oXL.Visible = false; object Missing = System.Reflection.Missing.Value; oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing)); oSheet = (Excel._Worksheet)oWB.ActiveSheet; /* //Add table headers going cell by cell. oSheet.Cells[1, 1] = "First Name"; oSheet.Cells[1, 2] = "Last Name"; oSheet.Cells[1, 3] = "Full Name"; oSheet.Cells[1, 4] = "Salary"; //Format A1:D1 as bold, vertical alignment = center. oSheet.get_Range("A1", "D1").Font.Bold = true; oSheet.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; */ // Create an array to multiple values at once. int iRows = grid1.Rows.Count + 1; int iCols = grid1.Columns.Count; string[,] saNames = new string[iRows, iCols]; for (int iCol = 1; iCol < grid1.Columns.Count; iCol++) { saNames[0, iCol - 1] = grid1.DisplayLayout.Bands[0].Columns[iCol].Header.Caption.ToString(); } for (int iRow = 0; iRow < grid1.Rows.Count; iRow++) { for (int iCol = 1; iCol < grid1.Columns.Count; iCol++) { saNames[iRow + 1, iCol - 1] = grid1.Rows[iRow].Cells[iCol].Value.ToString(); } } string sHeaderColumn = DecToAlphabet(iCols); oSheet.get_Range("A1", sHeaderColumn + iRows.ToString()).Font.Size = 9; oSheet.get_Range("A1", sHeaderColumn + iRows.ToString()).Value2 = saNames; //oXL.Visible = true; //oXL.UserControl = true; SaveFileDialog saveFile = new SaveFileDialog(); saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); saveFile.Title = "Excel 저장위치 지정"; saveFile.DefaultExt = "xlsx"; saveFile.Filter = "xlsx files(*.xlsx)|*.xlsx|xls files(*.xls)|*.xls"; saveFile.ShowDialog(); if (saveFile.FileNames.Length > 0) { foreach (string filename in saveFile.FileNames) { string savePath = filename; if (Path.GetExtension(savePath) == ".xls") { oWB.SaveAs(savePath, Excel.XlFileFormat.xlWorkbookNormal); } else if (Path.GetExtension(savePath) == ".xlsx") { oWB.SaveAs(savePath, Excel.XlFileFormat.xlOpenXMLWorkbook); } } } oWB.Close(); oXL.Quit(); oXL = null; oWB = null; oSheet = null; oRng = null; // } catch (Exception ex) { //ex } } | cs |
'C#' 카테고리의 다른 글
C# PING 테스트 (0) | 2021.02.23 |
---|---|
C# 카카오톡 핸들 찾기 (0) | 2021.02.23 |
C# FTP 파일 가져오기 & 파일 존재여부 (0) | 2019.09.23 |
C# 정규식을 이용하여 문자열이 숫자인지 판단 (0) | 2019.09.19 |
C# ListView 복사 붙여넣기 (0) | 2019.09.19 |