VB.NET 快速向Excel寫入大量數據


把數據以字符串的形式保存,不同列之前以Tab符隔開,不同行之間用回車換行符號:

思路是把所有數據在內存中以字符串的形式寫入到WINDOWS的粘貼板中,然后一次性粘貼到Excel中。

先添加引用“Microsoft.Office.Interop.Excel”

'先添加引用“Microsoft.Office.Interop.Excel”

Private Sub SaveToXls(StrData As String, StrFileName As String)
       If String.IsNullOrEmpty(StrData) Or String.IsNullOrEmpty(StrFileName) Then
           Return
       Else
           Dim xlApp As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
           If IsNothing(xlApp) Then
               MessageBox.Show("無法創建Excel對象,可能您的系統未安裝Excel")
           End If
           xlApp.DefaultFilePath = ""
           xlApp.DisplayAlerts = True
           xlApp.SheetsInNewWorkbook = 1
           Dim xlBook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Add(True)
           Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet = xlBook.Worksheets.Add()
           System.Windows.Forms.Clipboard.SetDataObject(StrData)
           xlSheet.Paste()
           xlBook.SaveAs(StrFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
 
           '以下代碼是結束Excel進程在系統中的占用,否則只用close和Quit,.NET框架並不能實時結束Excel進程。
           xlBook.Close()
           System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
           System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
           xlSheet = Nothing
           xlBook = Nothing
           xlApp.Quit()
           System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
           xlApp = Nothing
           GC.Collect()
       End If
   End Sub

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM