最近看到很多人分享NPOI的用法.

但是很多都不是完整示例或者並沒有實戰效果.

剛好最近有個VB.NET的項目有升級原有的oledb select sheet$的做法.

很明顯,NPOI有更好的穩定性和兼容性.

2進制的處理方式排除了server和client端有沒有office excel的諸多影響和限制.如office版本,系統編碼問題.以及server端是否需要安裝office excel.

2.0版本之後更是支持.xlsx格式等等..

那直接上代碼:

要先引用HSSF和XSSF(for .xlsx support).

下載Excel.沒有寫下載成xlsx的格式了.沒必要.如果一定要download成xlsx.使用對應的XSSF命名空間下的XSSFWorkbook等即可

Imports NPOI.HSSF.UserModel
Imports NPOI.XSSF.UserModel Public Shared Function DownLoadToExcel(ByVal dt As DataTable)
Dim book As HSSFWorkbook = New HSSFWorkbook()
Dim sheet As HSSFSheet = book.CreateSheet("Your_Sheet_Name")
Dim row As HSSFRow = sheet.CreateRow()
For i = To dt.Columns.Count -
row.CreateCell(i).SetCellValue(dt.Columns(i).ColumnName)
Next
For i = To dt.Rows.Count -
Dim row2 As HSSFRow = sheet.CreateRow(i + )
For j = To dt.Columns.Count -
row2.CreateCell(j).SetCellValue(dt.Rows(i)(j).ToString)
Next
Next
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream()
book.Write(ms)
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", Now.ToString))
HttpContext.Current.Response.BinaryWrite(ms.ToArray())
book = Nothing
ms.Close()
ms.Dispose()
End Function

上傳EXCEL.

通常我們實際做項目的時候,需要通過導入excel再進行處理而不是單純的重複insert DB.

那我們直接獲取datatable.

支持xls和.xlsx格式上傳. 這裏的lofile 就是HtmlInputFile控件.調用方法的時候直接將這個對象傳過來即可.

我這裏是web項目.如果是winform.lofile完全不用save之後再處理.直接傳path過來就可以.同樣請將對應的HttpContext改成Context.

Public Shared Function GetTabelFromExcel(ByVal lofile As HtmlInputFile) As DataTable

        Dim filepath As String = Path.Combine(HttpContext.Current.Server.MapPath("bin"), Path.GetFileName(lofile.PostedFile.FileName))
Dim fileExt As String = Path.GetExtension(lofile.PostedFile.FileName)
Try
lofile.PostedFile.SaveAs(filepath)
Dim tempname As String = Guid.NewGuid().ToString
Dim tempfilepath As String = Path.Combine(HttpContext.Current.Server.MapPath("bin"), tempname & fileExt)
File.Move(filepath, tempfilepath)
File.Delete(filepath)
filepath = tempfilepath
If fileExt = ".xlsx" Then '.xlsx 2007
Try
Dim wb As XSSFWorkbook
Dim file As System.IO.FileStream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Using file
wb = New XSSFWorkbook(file)
End Using
Dim sheet As XSSFSheet = CType(wb.GetSheetAt(0), XSSFSheet)
Dim rows As System.Collections.IEnumerator = sheet.GetRowEnumerator()
Dim dt As DataTable = New DataTable()
For i As Integer = 0 To CInt(sheet.GetRow(0).LastCellNum) - 1
dt.Columns.Add(System.Convert.ToChar(65 + i).ToString())
Next
While rows.MoveNext()
Dim row As XSSFRow = CType(rows.Current, XSSFRow)
Dim dr As DataRow = dt.NewRow()
For j As Integer = 0 To CInt(row.LastCellNum) - 1
Dim cell As XSSFCell = CType(row.GetCell(j), XSSFCell)
If cell Is Nothing Then
dr(j) = Nothing
Else
dr(j) = cell.ToString()
End If
Next
dt.Rows.Add(dr)
End While
dt.Rows.RemoveAt(0)
Return dt
Catch e As System.Exception
Throw New Exception("文件第一行不允許有空白欄位或文件正在使用,請先關閉正在打開的文件!" & e.Message)
End Try
ElseIf fileExt = ".xls" Then 'office 2003
Try
Dim wb As HSSFWorkbook
Dim file As System.IO.FileStream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Using file
wb = New HSSFWorkbook(file)
End Using Dim sheet As HSSFSheet = CType(wb.GetSheetAt(0), HSSFSheet)
Dim rows As System.Collections.IEnumerator = sheet.GetRowEnumerator()
Dim dt As DataTable = New DataTable()
For i As Integer = 0 To CInt(sheet.GetRow(0).LastCellNum) - 1
dt.Columns.Add(System.Convert.ToChar(65 + i).ToString())
Next
While rows.MoveNext()
Dim row As HSSFRow = CType(rows.Current, HSSFRow)
Dim dr As DataRow = dt.NewRow()
For j As Integer = 0 To CInt(row.LastCellNum) - 1
Dim cell As HSSFCell = CType(row.GetCell(j), HSSFCell)
If cell Is Nothing Then
dr(j) = Nothing
Else
dr(j) = cell.ToString()
End If
Next
dt.Rows.Add(dr)
End While
dt.Rows.RemoveAt(0)
Return dt Catch e As System.Exception
Throw New Exception("文件第一行不允許有空白欄位或文件正在使用,請先關閉正在打開的文件!" & e.Message)
End Try
Else
Throw New Exception("請選擇office excel文件!")
End If Catch ex As Exception
Throw New Exception("請選擇office excel文件!" & ex.Message)
Finally
File.Delete(filepath)
End Try End Function

得到datatable之後請自行處理.  

關於NPOI的一點補充和示例的更多相关文章

  1. [Xamarin] 關於發出Notification 的大小事 (转帖)

    關於Anroid 的使用者來說,Notification 是一個非常會看到且用到的功能 他可以提醒使用者甚麼東西需要待處理,像是郵件或是會議的提醒等.. 甚至有些APP ,直接使用Notificati ...

  2. 在laravel下關於blade模板的嘗試

    Blade模板 關於模板繼承和分區段 @section和@yield的實驗 ①關於@section...@show嘗試 測試1 {{--appV2test.blade.php--}} <html ...

  3. 開博客了, 因為搞Delphi 開發的關於Delphi學習

    開博客了, 因為搞Delphi 開發的關於Delphi學習,之前都是用本地TXT文件保存,發現在本地電腦保存非常不方面,而且只能在一台電腦上保存,不容易查看和修改內容.便於以後的記錄只用,以及經驗交流 ...

  4. 關於Validform 控件 值得注意的地方

    Validform控件其實用起來挺方便的,直接百度就能找到官網,有直接的demo做參考.這些我就不提了,我所要說的是關於Validform控件的ajax的提交. Validform中有個參數ajaxP ...

  5. JDK1.6历史版本的下载(關於TLSv1.2)Oracle的官方文檔

    [资源描述]:对于部分老项目 仍然采用的是JDK1.6 版本 但是打开官方 JDK 都是最新的 版本 想找 历史版本 不容易找到 [资源详情]:提供下载链接: http://www.oracle.co ...

  6. 關於imagick不得不說的一些事

    PHP建圖通常都用GD庫,因為是內置的不需要在服務器上額外安裝插件,所以用起來比較省心,但是如果你的程序主要的功能就是處理圖像,那麼就不建議用GD了,因為GD不但低效能而且能力也比較弱,佔用的系統資源 ...

  7. 關於 WebClient wc = new WebClient() 下載第三方數據不能進安安信任異常

    報錯異常:The underlying connection was closed: Could not establish trust relationship for SSL/TLS secure ...

  8. Python 基礎 - 淺copy補充說明

    在 import copy 這個模塊裡 基於第一個列表來做淺copy,實際上第二個列表裡的元素,是第一個列表的 引用. 接下來介紹 淺copy有三種方式可以使用 #!/usr/bin/env pyth ...

  9. [Xamarin] 關於Internal Storage ,存取App內部使用資料 (转帖)

    最近在開發App,會使用到必須要處理一些App所使用的資料,上網路查一下Android 得作法,包含我自己也實作了一下,可能是因為對Java || Android 不是很孰悉,常常錯在 java.la ...

随机推荐

  1. ffmpeg 打开视频流太慢(下)

    前面的博文中已经交代过,ffmpeg打开视频慢主要是因为av_find_stream_info 耗时久.下面给出重写查找音视频stream info的一段代码,用来替代av_find_stream_i ...

  2. PHP中应用Service Locator服务定位及单例模式

    单例模式将一个对象实例化后,放在静态变量中,供程序调用. 服务定位(ServiceLocator)就是对象工场Factory,调用者对象直接调用Service Locator,与被调用对象减轻了依赖关 ...

  3. POJ 3723 Conscription 最小生成树

    题目链接: 题目 Conscription Time Limit: 1000MS Memory Limit: 65536K 问题描述 Windy has a country, and he wants ...

  4. EXT经验--查询EditorGridPanel的tbar的默认配置对象

    前言:EXT的API可谓熟悉EXT的葵花宝典,会看API可谓对于配置EXT,学习EXT最重要的基本功,这点相对于学习轻量级的Easyui来说更加明显. 比如下面的一段代码:注:在Ext.grid.Ed ...

  5. PHP开发框架[国内框架]

    1.Thinkphp  http://thinkphp.cn/ 2.Brophp   http://www.brophp.com/zf/ 由LAMP兄弟连打造 3.WindFramework http ...

  6. visual studio 2010运行速度提速

    前段时间为了一个项目而把VS2008换成了VS2010,结果原本就不堪重负的本本跑起VS2010来那更是慢得没话说,于是看了遍VS2010选项,又从网上到处找资料找优化方法,总算使我的VS2010跑得 ...

  7. A Step-by-Step Guide to Your First AngularJS App

    What is AngularJS? AngularJS is a JavaScript MVC framework developed by Google that lets you build w ...

  8. POJ 1930

    Dead Fraction Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 1762   Accepted: 568 Desc ...

  9. [LeetCode]Link List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...

  10. C#接口的经典案例

    C#接口(interface)实例子(简单而经典)2008/12/04 10:04using System; using System.Collections.Generic; using Syste ...