|
| 1 | +using System; |
| 2 | +using System.Reflection; |
| 3 | +using Excel = Microsoft.Office.Interop.Excel; |
| 4 | + |
| 5 | +namespace ExcelDemo |
| 6 | +{ |
| 7 | + class Program |
| 8 | + { |
| 9 | + public static void Main(string[] args) |
| 10 | + { |
| 11 | + Excel.Application excel; |
| 12 | + Excel.Workbook workbook; |
| 13 | + Excel.Worksheet sheet; |
| 14 | + Excel.Range range; |
| 15 | + |
| 16 | + try |
| 17 | + { |
| 18 | + // Start Excel and get Application object. |
| 19 | + excel = new Excel.Application(); |
| 20 | + excel.Visible = true; |
| 21 | + |
| 22 | + // Get a new workbook. |
| 23 | + workbook = excel.Workbooks.Add(Missing.Value); |
| 24 | + sheet = (Excel.Worksheet)workbook.ActiveSheet; |
| 25 | + |
| 26 | + // Add table headers going cell by cell. |
| 27 | + sheet.Cells[1, 1] = "First Name"; |
| 28 | + sheet.Cells[1, 2] = "Last Name"; |
| 29 | + sheet.Cells[1, 3] = "Full Name"; |
| 30 | + sheet.Cells[1, 4] = "Salary"; |
| 31 | + |
| 32 | + // Format A1:D1 as bold, vertical alignment = center. |
| 33 | + sheet.get_Range("A1", "D1").Font.Bold = true; |
| 34 | + sheet.get_Range("A1", "D1").VerticalAlignment = |
| 35 | + Excel.XlVAlign.xlVAlignCenter; |
| 36 | + |
| 37 | + // Create an array to multiple values at once. |
| 38 | + string[,] saNames = new string[5, 2]; |
| 39 | + |
| 40 | + saNames[0, 0] = "John"; |
| 41 | + saNames[0, 1] = "Smith"; |
| 42 | + saNames[1, 0] = "Tom"; |
| 43 | + saNames[1, 1] = "Brown"; |
| 44 | + saNames[2, 0] = "Sue"; |
| 45 | + saNames[2, 1] = "Thomas"; |
| 46 | + saNames[3, 0] = "Jane"; |
| 47 | + saNames[3, 1] = "Jones"; |
| 48 | + saNames[4, 0] = "Adam"; |
| 49 | + saNames[4, 1] = "Johnson"; |
| 50 | + |
| 51 | + // Fill A2:B6 with an array of values (First and Last Names). |
| 52 | + sheet.get_Range("A2", "B6").Value2 = saNames; |
| 53 | + |
| 54 | + // Fill C2:C6 with a relative formula (=A2 & " " & B2). |
| 55 | + range = sheet.get_Range("C2", "C6"); |
| 56 | + range.Formula = "=A2 & \" \" & B2"; |
| 57 | + |
| 58 | + // Fill D2:D6 with a formula(=RAND()*100000) and apply format. |
| 59 | + range = sheet.get_Range("D2", "D6"); |
| 60 | + range.Formula = "=RAND()*100000"; |
| 61 | + range.NumberFormat = "$0.00"; |
| 62 | + |
| 63 | + // AutoFit columns A:D. |
| 64 | + range = sheet.get_Range("A1", "D1"); |
| 65 | + range.EntireColumn.AutoFit(); |
| 66 | + |
| 67 | + // Make sure Excel is visible and give the user control |
| 68 | + // of Microsoft Excel's lifetime. |
| 69 | + excel.Visible = true; |
| 70 | + excel.UserControl = true; |
| 71 | + } |
| 72 | + catch (Exception e) |
| 73 | + { |
| 74 | + Console.WriteLine($"Error: {e.Message} Line: {e.Source}"); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments