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 |
using System; using System.Windows.Forms; // 参照の追加>COM>Microsoft Excel 16.0 Object Library namespace ProductionManagement { class Excel { public void CreateBook() { if (Type.GetTypeFromProgID("Excel.Application") == null) return; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = "title"; saveFileDialog.Filter = "xlsx | *.xlsx"; if (saveFileDialog.ShowDialog() != DialogResult.OK) return; var excel = new Microsoft.Office.Interop.Excel.Application(); excel.DisplayAlerts = false; var books = excel.Workbooks; var book = books.Add(); var sheets = book.Sheets; var sheet = sheets[1]; var cells = sheet.cells; WriteCell(cells, "Hello World", 2, 2); book.SaveCopyAs(saveFileDialog.FileName); ComRelease(cells); ComRelease(sheet); ComRelease(sheets); book.Close(); ComRelease(book); ComRelease(books); excel.DisplayAlerts = true; excel.Quit(); ComRelease(excel); MessageBox.Show("終了しました。"); } private void WriteCell(dynamic cells, string value, int r, int c) { var cell = cells[r, c]; cell.value = value; ComRelease(cell); } private void ComRelease(dynamic target) { System.Runtime.InteropServices.Marshal.ReleaseComObject((object)target); target = null; } } } |