VB.NET 快速向Excel写入大量数据

本文介绍了一种将数据以字符串形式保存,并通过复制粘贴的方式导入到Excel的方法。此方法利用了.NET Framework中的Microsoft.Office.Interop.Excel库来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把数据以字符串的形式保存,不同列之前以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

 

转载于:https://www.cnblogs.com/jmpep/archive/2013/05/20/4486282.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值