2014年9月26日 星期五

NPOI 2教程 – 读取Word 2007文件

NPOI 2教程 – 读取Word 2007文件




NPOI 1.2.4 / 1.2.5 教程 – 2.2.4 设置单元格边框


NPOI 1.2.4教程 – 2.2.1 设置单元格格式


NPOI 產生Excel檔

NPOI 產生Excel檔

http://tankhylin.pixnet.net/blog/post/164676363-%5Basp.net%5D-npoi-%E7%94%A2%E7%94%9Fexcel%E6%AA%94

Imports System.Data.SqlClient
Imports System.Text
Imports System.IO
'== for Excel file Export ==
Imports NPOI.HSSF.UserModel
Imports NPOI.HPSF
Imports NPOI.POIFS.FileSystem
Dim strSql As New StringBuilder, SqlCmd As SqlCommand, dr As SqlDataReader
Dim workbook As HSSFWorkbook = New HSSFWorkbook()
Dim ms As MemoryStream = New MemoryStream() '==需要 System.IO命名空間
'設定檔案摘要(原始檔案部份)
Dim dsi As NPOI.HPSF.DocumentSummaryInformation = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation()
dsi.Company = "XXX公司"
workbook.DocumentSummaryInformation = dsi
'設定檔案摘要(說明部份)
Dim si As NPOI.HPSF.SummaryInformation = NPOI.HPSF.PropertySetFactory.CreateSummaryInformation()
si.Subject = "XXX報表"
workbook.SummaryInformation = si
'TITLE STYLE ----
Dim Font_Title As HSSFFont = workbook.CreateFont()
With Font_Title
      .Color = NPOI.HSSF.Util.HSSFColor.WHITE.index
      .FontName = HSSFFont.FONT_ARIAL
      .FontHeightInPoints = 10
      .Boldweight = NPOI.SS.UserModel.FontBoldWeight.BOLD
End With
Dim Style_Title As HSSFCellStyle = workbook.CreateCellStyle()
With Style_Title
      '儲存格網底顏色
      .FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LIGHT_BLUE.index
      .FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND
      '儲存格框線
      .BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderRight = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderTop = NPOI.SS.UserModel.BorderStyle.THIN
      .BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .SetFont(Font_Title)
End With
'BODY STYLE ----
Dim Font_Body As HSSFFont = workbook.CreateFont()
With Font_Body
      .Color = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .FontName = HSSFFont.FONT_ARIAL
      .FontHeightInPoints = 10
End With
Dim Style_Body As HSSFCellStyle = workbook.CreateCellStyle()
With Style_Body
      '儲存格網底顏色
      .FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index
      .FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND
      '儲存格框線
      .BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderRight = NPOI.SS.UserModel.BorderStyle.THIN
      .BorderTop = NPOI.SS.UserModel.BorderStyle.THIN
      .BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index
      .SetFont(Font_Body)
End With
'== 新增試算表 Sheet名稱。
Dim u_sheet1 As HSSFSheet = workbook.CreateSheet("表1")
Using cnSql As New SqlConnection(gstrConnDB)
      cnSql.Open()
      strSql.Length = 0
      strSql.AppendLine("Select distinct DATE,A,B,C ")
      strSql.AppendLine("From TABLE ")
      strSql.AppendLine("Where Substring(Deliver_Dt, 1, 6) = '" & gstrQryDate & "' ")
      strSql.AppendLine("Order by Deliver_Dt")
      SqlCmd = New SqlCommand(strSql.ToString, cnSql)
      dr = SqlCmd.ExecuteReader
      Dim HSRow As HSSFRow, HSCell As HSSFCell
      HSRow = u_sheet1.CreateRow(0)
      For i As Integer = 0 To 21
            HSCell = HSRow.CreateCell(i)
            Select Case i
                  Case "0"
                        HSCell.SetCellValue("日期")
                 Case "1"
                       HSCell.SetCellValue("AAA")
                 Case "2"
                       HSCell.SetCellValue("BBB")
                 Case "3"
                       HSCell.SetCellValue("CCC")
            End Select
            HSCell.CellStyle = Style_Title
      Next
      '== 利用迴圈,把資料寫入 Excel各個儲存格裡面。
      Dim k As Integer = 1
      While dr.Read()
            HSRow = u_sheet1.CreateRow(k)
            For i = 0 To (dr.FieldCount - 1)
                  HSCell = HSRow.CreateCell(i)
                  HSCell.SetCellValue(dr.GetValue(i).ToString())
                  HSCell.CellStyle = Style_Body
            Next
            k = k + 1
      End While
      SqlCmd.Cancel()
      dr.Close()
End Using
workbook.Write(ms)
ms.Flush()
ms.Position = 0
Dim myFile As System.IO.FileStream = System.IO.File.Open("D:\BOOK_" & gstrQryDate & ".xls", IO.FileMode.OpenOrCreate)
ms.WriteTo(myFile)
ms.Close()
ms.Dispose()

參考:

NPOI Excel合併儲存格


http://no2don.blogspot.com/2014/05/c-npoi-excel.html

可參考: http://no2don.blogspot.com/2013/02/c-nopi-excel-xls.html

合併儲存格最重要的Code :

var workbook = new HSSFWorkbook();
var sheetReportResult = workbook.CreateSheet("報表結果");
 //產生第一個要用CreateRow 
sheetReportResult.CreateRow(0).CreateCell(0).SetCellValue("客戶資料");
 
//建立跨越五列(共六列 1~6)  ,跨越三欄(共四欄 A~D)
sheetReportResult.AddMergedRegion(new CellRangeAddress(0, 5, 0, 3));
重點在最後一行進行合併
合併後,塞資料方法一如往常,只是請注意,已經跨越的攔或列都必須要計算進去




[NPOI 2.0] ASP.NET 輸出 Excel 2007

http://tw.gigacircle.com/794887-1

原文為本人撰寫 -- [NPOI 2.0] ASP.NET 輸出 Excel (.xlsx檔 2007格式) -- ASP.NET Export to Excel (.xlsx)
http://www.dotblogs.com.tw/mis2000lab/archive/2014/07/02/npoi-20-for-aspnet_20140703.aspx


NPOI 升級成 2.0 囉 
檔案下載 -- https://npoi.codeplex.com/releases
下載後,請把 .DLL檔案(共計五個),在Visual Studio的網站或專案中,加入參考


實作過程中,因為原廠找不到範例,
特別感謝前輩的分享:
Bobby -- http://smlboby.blogspot.tw/2013/07/npoi-20.html 很有用!謝謝~


只要記住一點,就能初步升級
命名空間 or 程式內,有HSSF字樣,就是產生 Excel 2003(含)以前的格式, .xls檔案
修正為 XSSF即可產生 .xlsx檔(Excel 2007(含)後續新版本的檔案)

上一版(1.2.4版的寫法大多可以沿用),請您放心

1. 命名空間。請自己加入
//-- 自己寫的(宣告)--
using System.IO; //-- FileStream會用到這個命名空間

//===============================
// NPOI 2.0的命名空間與 .DLL檔案(加入參考) ----
// HSSF(Excel 2003), XSSF(Excel 2007), XWPF(Word 2007)。 
//using NPOI.HSSF.UserModel; //-- HSSF 用來產生Excel 2003檔案(.xls)
using NPOI.XSSF.UserModel; //-- XSSF 用來產生Excel 2007檔案(.xlsx)

using NPOI.SS.UserModel; //-- v.1.2.4起 新增的。
//===============================


2. 後置程式碼
//命名空間。using NPOI.XSSF.UserModel; 
IWorkbook workbook = new XSSFWorkbook(); //-- XSSF 用來產生Excel 2007檔案(.xlsx)


//== 新增試算表。===================================
//== 生成一個空白的 Excel 檔案,並且添加三個指定名稱的試算表 Sheet

//-- XSSF 用來產生Excel 2007檔案(.xlsx)

// 方法一: 感謝 Bobby前輩的範例 
XSSFSheet u_sheet = (XSSFSheet)workbook.CreateSheet("My Sheet_20方法一");

// 方法二: v.1.2.4版起的寫法 ( NPOI 2.0可運作)
//== 新增試算表 Sheet名稱。使用 NPOI.SS.UserModel命名空間。
//ISheet u_sheet = (ISheet)workbook.CreateSheet("My Sheet_20方法二");

//== 輸出Excel 2007檔案。==============================
MemoryStream MS = new MemoryStream(); //==需要 System.IO命名空間
workbook.Write(MS);

//== Excel檔名,請寫在最後面 filename的地方
Response.AddHeader("Content-Disposition", "attachment; filename=EmptyWorkbook_2007_1.xlsx");
Response.BinaryWrite(MS.ToArray());

//== 釋放資源
workbook = null; //== VB為 Nothing
MS.Close();
MS.Dispose();



3. 常見的錯誤

如果您採用了 NPOI 2.0的寫法(使用到 XSSF)
但您產生的副檔名,仍是舊版 .xls

程式可以正常執行,但打開 Excel檔,裡面卻是 HTML原始碼,而非您想輸出的資料!

只要把上面程式的最後一段,輸出的 Excel副檔名改成 .xlsx即可!


VB + C# 兩種範例都有
範例下載:[NPOI 2.0] ASP.NET 輸出 Excel (.xlsx檔 2007格式) -- ASP.NET Export to Excel (.xlsx)
http://www.dotblogs.com.tw/mis2000lab/archive/2014/07/02/npoi-20-for-aspnet_20140703.aspx


Ref:
http://blog.xuite.net/sugopili/computerblog/66186028-NPOI+2.0



2014年9月23日 星期二

C#和VB代碼轉換





隱藏GridView中欄位如何取值

http://www.dotblogs.com.tw/eason.yen/archive/2011/01/31/21164.aspx

1protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
2{
3  if(e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
4  {
5   //要隱藏的欄位   
6    e.Row.Cells[1].Visible = false;      
7  }          
8}

http://demo.tc/Post/88

第一種方式算是比較小技巧的我們再GridView的RowCreated事件中撰寫以下code
  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 
  2.     { 
  3. if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header) 
  4.             e.Row.Cells[0].Visible = false

然後在RowDataBound事件中,一樣可以利用Row.Cells的方式找到它
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
  2.     { 
  3.         if (e.Row.RowType == DataControlRowType.DataRow) 
  4.         { 
  5.             string aa = e.Row.Cells[0].Text; 
  6.         } 
  7.     } 
原因很簡單因為RowCreated事件晚於DataBinding所以它在bind以後才被隱藏當然你在RowDataBound就可以找到資料了

第二種方式看起來就比較有點水準@@
我們是直接使用ui介面把某個欄位隱藏起來(Visible = False),然後直接指定DataItem的方式去找到它,我們需要在RowDataBound事件撰寫以下code
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
  2.     { 
  3.         if (e.Row.RowType == DataControlRowType.DataRow) 
  4.         { 
  5.             Boolean draft = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "draft")); 
  6.             if (draft == true
  7.                 e.Row.ForeColor = System.Drawing.Color.Green; 
  8.         } 
  9.     } 
以上的code我是把draftx欄位轉換成布林,然後去判斷是真是假再去對該ROW的字色作變換