VB.NET Generate Excel 檔案
係Project上 "Add Reference" -> "Microsoft.Office.Interop.Excel (Version 14.0.0.0)"
係Application Form上加 Microsoft.Office.Interop.Excel 既Library
VB.NET Generate Excel 檔案 |
Imports Excel = Microsoft.Office.Interop.Excel Private Sub Create_Excel() Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") Generate_SpreedSheet(xlWorkSheet) xlWorkSheet.SaveAs("C:\result.xls") xlWorkBook.Close() xlApp.Quit() ReleaseObject(xlApp) ReleaseObject(xlWorkBook) ReleaseObject(xlWorkSheet) MsgBox("Excel file created , you can find the file C:\result.xls") End Sub Private Sub ReleaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub Private Sub Generate_SpreedSheet(ByRef A As Excel.Worksheet) For o As Integer = 1 To 10 A.Cells(o + 1, 1) = o.ToString Next For k As Integer = 1 To 10 A.Cells(1, k + 1) = k.ToString Next For i As Integer = 1 To 10 For j As Integer = 1 To 10 A.Cells(i + 1, j + 1) = (i * j).ToString Next Next End Sub |