VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • 通过vb.net 和NPOI实现对excel的读操作

通过vb.net 和NPOI实现对excel的读操作,很久很久前用过vb,这次朋友的代码是vb.net写的需要一个excel的操作,

就顾着着实现功能了,大家凑合着看吧


		
  1.  
    Option Explicit On
  2.  
     
  3.  
    Imports NPOI.SS.UserModel
  4.  
    Imports System.IO
  5.  
     
  6.  
    Public Class ExcelHelper
  7.  
     
  8.  
    Public Shared Function ImportExcel(ByVal strSource As String) As DataTable
  9.  
    Dim hssfWorkbook As IWorkbook
  10.  
    Dim sheet As ISheet
  11.  
    Dim rows As System.Collections.IEnumerator
  12.  
    Dim dt As DataTable
  13.  
    Dim icount As Int32
  14.  
    Dim row As IRow
  15.  
    Dim dr As DataRow
  16.  
    Dim cell As ICell
  17.  
     
  18.  
    hssfWorkbook = WorkbookFactory.Create(FileToStream(strSource))
  19.  
     
  20.  
     
  21.  
    sheet = hssfWorkbook.GetSheetAt(0)
  22.  
    rows = sheet.GetRowEnumerator()
  23.  
     
  24.  
    icount = 0
  25.  
    dt = New DataTable()
  26.  
     
  27.  
    While rows.MoveNext()
  28.  
     
  29.  
    icount = icount + 1
  30.  
    row = rows.Current
  31.  
    dr = dt.NewRow
  32.  
    For i As Int32 = 0 To row.LastCellNum
  33.  
    cell = row.GetCell(i)
  34.  
    If cell Is Nothing Then
  35.  
    'dr(i) = DBNull.Value
  36.  
    Else
  37.  
    If icount = 1 Then
  38.  
    dt.Columns.Add(cell.ToString)
  39.  
    End If
  40.  
     
  41.  
    dr(i) = cell.ToString
  42.  
    End If
  43.  
     
  44.  
    Next
  45.  
     
  46.  
    dt.Rows.Add(dr)
  47.  
     
  48.  
    End While
  49.  
     
  50.  
    dt.Rows.RemoveAt(0)
  51.  
     
  52.  
    Return dt
  53.  
     
  54.  
    End Function
  55.  
     
  56.  
    Public Shared Function FileToStream(ByVal fileName As String) As Stream
  57.  
     
  58.  
    '打开文件
  59.  
     
  60.  
    Dim fileStream As FileStream
  61.  
     
  62.  
    fileStream = New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)
  63.  
     
  64.  
    '读取文件的 byte()
  65.  
     
  66.  
    Dim bytes() As Byte = New Byte(fileStream.Length) {}
  67.  
     
  68.  
    fileStream.Read(bytes, 0, bytes.Length)
  69.  
     
  70.  
    fileStream.Close()
  71.  
     
  72.  
    '把 byte()转换成 Stream
  73.  
     
  74.  
    Dim stream As Stream = New MemoryStream(bytes)
  75.  
     
  76.  
    Return stream
  77.  
     
  78.  
    End Function
  79.  
     
  80.  
    End Class

 

转载于:https://www.cnblogs.com/realso/p/8275736.html


相关教程