<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NPOI &#8211; Ling&#039;s Note</title>
	<atom:link href="https://www.chunho-ling.com/category/computing/programming/applicationframework/npoi/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.chunho-ling.com</link>
	<description>Everything related IT, and me.</description>
	<lastBuildDate>Fri, 12 Jan 2018 07:07:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">104401516</site>	<item>
		<title>[NPOI] 解決Cell Formula 計算錯誤</title>
		<link>https://www.chunho-ling.com/npoi-%e8%a7%a3%e6%b1%bacell-formula-%e8%a8%88%e7%ae%97%e9%8c%af%e8%aa%a4/</link>
					<comments>https://www.chunho-ling.com/npoi-%e8%a7%a3%e6%b1%bacell-formula-%e8%a8%88%e7%ae%97%e9%8c%af%e8%aa%a4/#respond</comments>
		
		<dc:creator><![CDATA[C.H. Ling]]></dc:creator>
		<pubDate>Fri, 12 Jan 2018 07:07:40 +0000</pubDate>
				<category><![CDATA[Application Framework 程式框架]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[NPOI]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://www.chunho-ling.com/?p=812</guid>

					<description><![CDATA[用NPOI 時, 當存取的cell 為方程式時, 會有機會因為它將小數當做double 計算而出錯.&#160;在 C# 中, double 與 decimal 最大分別是double 為浮位數 (Floating point), 即是它會用byte 進在儲存和運算. 而decimal 則是用十位數進行.&#160; 在專案中, 因為要保存格式, 故用cell的dataformat 進行轉換, 若轉換不到才用回原本的CellNumericValue. 部份程式碼如下: // NPOI issue, it will calculate value in double format, <a class="mh-excerpt-more" href="https://www.chunho-ling.com/npoi-%e8%a7%a3%e6%b1%bacell-formula-%e8%a8%88%e7%ae%97%e9%8c%af%e8%aa%a4/" title="[NPOI] 解決Cell Formula 計算錯誤">[...]</a>]]></description>
										<content:encoded><![CDATA[<p>用NPOI 時, 當存取的cell 為方程式時, 會有機會因為它將小數當做double 計算而出錯.&nbsp;<span id="more-812"></span>在 C# 中, double 與 decimal 最大分別是double 為浮位數 (Floating point), 即是它會用byte 進在儲存和運算. 而decimal 則是用十位數進行.&nbsp;</p>
<p>在專案中, 因為要保存格式, 故用cell的dataformat 進行轉換, 若轉換不到才用回原本的CellNumericValue. 部份程式碼如下:</p>
<pre class="lang:default decode:true "> // NPOI issue, it will calculate value in double format, so need to change in string format with cell data format and convert back to double.
                                                // Append below if any specif char. found.
                                                double castValue;
                                                bool castResult=  double.TryParse(cell.NumericCellValue.ToString(cell.CellStyle.GetDataFormatString())
                                                    .Replace(",", "")
                                                    .Replace("_", "")
                                                    .Replace("(", "")
                                                    .Replace(")", "")
                                                    .Replace("$", "")
                                                    , out castValue);
                                                if (castResult == false)
                                                    castValue = cell.NumericCellValue;
                                                dr[i] = castValue;</pre>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.chunho-ling.com/npoi-%e8%a7%a3%e6%b1%bacell-formula-%e8%a8%88%e7%ae%97%e9%8c%af%e8%aa%a4/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">812</post-id>	</item>
		<item>
		<title>[NPOI] 讀取Excel 檔案內容</title>
		<link>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-%e6%aa%94%e6%a1%88%e5%85%a7%e5%ae%b9/</link>
					<comments>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-%e6%aa%94%e6%a1%88%e5%85%a7%e5%ae%b9/#respond</comments>
		
		<dc:creator><![CDATA[C.H. Ling]]></dc:creator>
		<pubDate>Mon, 04 Sep 2017 09:11:15 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[NPOI]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://www.chunho-ling.com/?p=734</guid>

					<description><![CDATA[進行SI 時, 總會遇到比較經典的File base 整合案例, Excel 便是其中一例. 在此示範如何存取Excel 檔案.在此建立了一個ExcelHelper 進行Excel 相關的存取動作. ExcelHelper.cs public class ExcelHelper { public DataTable readExcelToDataTable(string filePath, int sheetNum, int headerLine, int contentLine) { this.loadExcelFile(filePath); this.resetCurrentDataTable(); this.readExcelHeader(sheetNum, headerLine, contentLine); return this.readExcelData(sheetNum, contentLine); <a class="mh-excerpt-more" href="https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-%e6%aa%94%e6%a1%88%e5%85%a7%e5%ae%b9/" title="[NPOI] 讀取Excel 檔案內容">[...]</a>]]></description>
										<content:encoded><![CDATA[<p>進行SI 時, 總會遇到比較經典的File base 整合案例, Excel 便是其中一例. 在此示範如何存取Excel 檔案.<span id="more-734"></span>在此建立了一個ExcelHelper 進行Excel 相關的存取動作.</p>
<p>ExcelHelper.cs</p>
<pre class="lang:default decode:true "> public class ExcelHelper
    {
public DataTable readExcelToDataTable(string filePath, int sheetNum, int headerLine, int contentLine)
        {
            this.loadExcelFile(filePath);
            this.resetCurrentDataTable();
            this.readExcelHeader(sheetNum, headerLine, contentLine);
            return this.readExcelData(sheetNum, contentLine);     //line 0 is header, data start from line 1
        }
 public void loadExcelFile(string filePath)
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                currentExcelFileType = Path.GetExtension(filePath);

                if (currentExcelFileType == ExcelFileType.xls)
                {
                    currentWorkbook = new HSSFWorkbook(file);
                }
                else if (currentExcelFileType == ExcelFileType.xlsx)
                {
                    currentWorkbook = new XSSFWorkbook(file);
                }
            }
        }
 public void resetCurrentDataTable()
        {
            currentTable = new DataTable();
        }
public void readExcelHeader(int sheetNum, int headerline, int contentline)
        {
            ISheet sheet = currentWorkbook.GetSheetAt(sheetNum);
            IRow row = sheet.GetRow(headerline);
            IRow contentRow = sheet.GetRow(contentline);
            

            for (int i = 0; i &lt; row.LastCellNum; i++)
            {
                ICell cell = row.GetCell(i);
                ICell contentCell = contentRow.GetCell(i);

                // Handle incorrect format import if 1st content row has empty data.
                while (contentCell.IsCellEmpty())
                {
                    contentRow = sheet.GetRow(contentline++);
                    contentCell = contentRow.GetCell(i);
                }

                // Base on content value to decide Data coulumn type.
                if ((cell != null) &amp;&amp; (contentCell != null))
                {
                    // ToDo: Refactor repeatable code.
                    if (contentCell.CellType == CellType.Numeric)
                    {
                        // Handle date time format.
                        if (HSSFDateUtil.IsCellDateFormatted(contentCell))
                            this.addImportTableColumn(cell.StringCellValue, TableColumnType.DateTime);
                        else
                            this.addImportTableColumn(cell.StringCellValue, TableColumnType.Decimal);
                    }
                    else if (contentCell.CellType == CellType.Formula)
                    {
                        switch (contentCell.CachedFormulaResultType)
                        {
                            case CellType.String:
                                this.addImportTableColumn(cell.StringCellValue, TableColumnType.String);
                                break;
                            case CellType.Numeric:
                                if (HSSFDateUtil.IsCellDateFormatted(contentCell))
                                    this.addImportTableColumn(cell.StringCellValue, TableColumnType.DateTime);
                                else
                                    this.addImportTableColumn(cell.StringCellValue, TableColumnType.Decimal);
                                break;
                        }
                    }
                    else if (contentCell.CellType == CellType.String)
                    {
                        this.addImportTableColumn(cell.StringCellValue, TableColumnType.String);
                    }
                    else
                    {
                        this.addImportTableColumn(cell.StringCellValue, TableColumnType.String);
                    }
                }
            }

        }
 public DataTable readExcelData(int sheetNum, int offsetLineNum)
        {
            ISheet sheet = currentWorkbook.GetSheetAt(sheetNum);
            int numOfRows = sheet.LastRowNum;

            for (int r = offsetLineNum; r &lt; numOfRows - 1; r++)
            {
                IRow row = sheet.GetRow(r);
                DataRow dr = currentTable.NewRow();

                for (int i = 0; i &lt; row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    
                    if (cell == null)
                    {
                        dr[i] = null;
                        
                    }
                    else
                    {
                        if ((cell.CellType == CellType.Numeric) &amp;&amp; (currentTable.Columns[i].DataType.IsNumericType()))
                        {
                            if (HSSFDateUtil.IsCellDateFormatted(cell))
                                dr[i] = cell.DateCellValue;
                            else
                                dr[i] = cell.NumericCellValue;
                        }
                        else if (cell.CellType == CellType.Formula)
                        {
                            switch (cell.CachedFormulaResultType)
                            {
                                case CellType.String:
                                    dr[i] = cell.StringCellValue;
                                    break;
                                case CellType.Numeric:
                                    if (HSSFDateUtil.IsCellDateFormatted(cell))
                                        dr[i] = cell.DateCellValue;
                                    else
                                        dr[i] = cell.NumericCellValue;
                                    break;
                            }
                        }
                        else if (cell.CellType == CellType.String)
                        {
                            dr[i] = cell.StringCellValue;
                        }
                        // Create default empty value.
                        else if (cell.IsCellEmpty())
                        {
                            dr[i] = Activator.CreateInstance(currentTable.Columns[i].DataType);
                        }
                        else
                        {
                            dr[i] = cell.ToString();
                        }
                    }
                }

                currentTable.Rows.Add(dr);
            }

            return currentTable;
        }
}</pre>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-%e6%aa%94%e6%a1%88%e5%85%a7%e5%ae%b9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">734</post-id>	</item>
		<item>
		<title>[NPOI] 讀取Excel File</title>
		<link>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-file/</link>
					<comments>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-file/#respond</comments>
		
		<dc:creator><![CDATA[C.H. Ling]]></dc:creator>
		<pubDate>Tue, 21 Mar 2017 09:01:57 +0000</pubDate>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[NPOI]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Visual Basic]]></category>
		<guid isPermaLink="false">http://www.chunho-ling.com/?p=612</guid>

					<description><![CDATA[於程式中存取Excel File作大量數據的import / export 是正常事. 然而之前總須要於電腦中安裝Microsoft Office 才可以透過CreateObject() 進行. 在它將了Document standard 轉成XML後, 坊間已經有library 可以存取檔案內容, 不用再令伺服器如此擁腫. NPOI 是一套以POI 為基礎的Library, 它可以存取Word / Excel / PowerPoint / Outlook / Visio 及Publisher 檔案. 因為工作需要, 所以只研究了Excel 方面. 在示範中會讀取Excel 檔案並將內容顯示在DataGrid 內. <a class="mh-excerpt-more" href="https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-file/" title="[NPOI] 讀取Excel File">[...]</a>]]></description>
										<content:encoded><![CDATA[<p>於程式中存取Excel File作大量數據的import / export 是正常事. 然而之前總須要於電腦中安裝Microsoft Office 才可以透過CreateObject() 進行. 在它將了Document standard 轉成XML後, 坊間已經有library 可以存取檔案內容, 不用再令伺服器如此擁腫.<span id="more-612"></span></p>
<p>NPOI 是一套以POI 為基礎的Library, 它可以存取Word / Excel / PowerPoint / Outlook / Visio 及Publisher 檔案. 因為工作需要, 所以只研究了Excel 方面. 在示範中會讀取Excel 檔案並將內容顯示在DataGrid 內.</p>
<p>MainWindow.xaml</p>
<pre class="lang:default decode:true" title="MainWindow.xaml">&lt;Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PoC.NPOI.Excel.VB"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"&gt;
    &lt;Window.Resources&gt;
        &lt;Style TargetType="{x:Type Control}"&gt;
            &lt;Setter Property="Margin" Value="10" /&gt;
        &lt;/Style&gt;
        &lt;Style TargetType="Button"&gt;
            &lt;Setter Property="Width" Value="120" /&gt;
            &lt;Setter Property="Margin" Value="10" /&gt;
        &lt;/Style&gt;
    &lt;/Window.Resources&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height="Auto" /&gt;
            &lt;RowDefinition Height="*" /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;StackPanel Grid.Row="0"&gt;
            &lt;Grid&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width="Auto" /&gt;
                    &lt;ColumnDefinition Width="*" /&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;StackPanel Grid.Column="0"&gt;
                    &lt;Button Width="100" Name="btnImport" Click="btnImport_Click"&gt;Import&lt;/Button&gt;
                &lt;/StackPanel&gt;
                &lt;StackPanel Grid.Column="1" Orientation="Horizontal"&gt;
                    &lt;TextBlock Text="Path: "/&gt;
                    &lt;TextBlock Name="txtPath" /&gt;
                &lt;/StackPanel&gt;
            &lt;/Grid&gt;
        &lt;/StackPanel&gt;
        &lt;DataGrid Grid.Row="1" Name="dgFileContent" HorizontalAlignment="Stretch" ItemsSource="{Binding }" /&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p>MainWindow.xaml.vb</p>
<pre class="lang:default decode:true ">Imports System.Data
Imports System.IO
Imports Microsoft.Win32
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports NPOI.XSSF.UserModel

Class MainWindow

    Public dataTable As DataTable

    Private Sub btnImport_Click(sender As Object, e As RoutedEventArgs)
        ' Create Dialog and get input file.
        Dim openFileDialog As OpenFileDialog = New OpenFileDialog() With
        {
            .Filter = "Excel 97-2000 Files (*.xls; *.xlsx)|*.xls; *.xlsx|Comma spearated Files (*.csv)|*.csv",
            .Multiselect = False
        }
        Dim openResult As Boolean?
        openResult = openFileDialog.ShowDialog(Me)

        ' Get file content and update datagrid.
        If (openResult.HasValue) And (openResult) Then
            ' Update text block.
            Me.txtPath.Text = openFileDialog.FileName

            Using fileStream As FileStream = openFileDialog.OpenFile()
                ' Open file and get first sheet.
                Dim excelWorkBook As IWorkbook
                Select Case Path.GetExtension(openFileDialog.FileName).ToUpper()
                    Case ".XLSX"
                        excelWorkBook = New XSSFWorkbook(fileStream)
                    Case Else
                        excelWorkBook = New HSSFWorkbook(fileStream)
                End Select

                Dim excelSheet As ISheet = excelWorkBook.GetSheetAt(0)

                If (excelSheet IsNot Nothing) Then
                    dataTable = New DataTable()
                    ' Create column for datatable.
                    Dim refRow As IRow = excelSheet.GetRow(0)
                    For c = refRow.FirstCellNum To refRow.LastCellNum - 1
                        Select Case refRow.GetCell(c).CellType
                            Case CellType.Numeric
                                dataTable.Columns.Add(New DataColumn("Header" &amp; c, GetType(Decimal)))
                            Case CellType.String
                                dataTable.Columns.Add(New DataColumn("Header" &amp; c, GetType(String)))
                            Case Else
                                dataTable.Columns.Add(New DataColumn("Header" &amp; c, GetType(String)))
                        End Select
                    Next

                    ' Get each row and column data and add to DataGrid.
                    For r = 0 To excelSheet.LastRowNum - 1
                        Dim excelRow As IRow = excelSheet.GetRow(r)
                        Dim dataRow As DataRow = dataTable.NewRow()

                        For c = 0 To excelRow.LastCellNum - 1
                            dataRow(c) = excelRow.GetCell(c)
                        Next
                        dataTable.Rows.Add(dataRow)
                    Next
                    dgFileContent.DataContext = dataTable.DefaultView
                End If
            End Using
        End If
    End Sub
End Class
</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.chunho-ling.com/npoi-%e8%ae%80%e5%8f%96excel-file/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">612</post-id>	</item>
	</channel>
</rss>
