1. 程式人生 > >C#NPOI讀取Excel

C#NPOI讀取Excel

	                /// <summary>
			/// 2007版Excel
			/// </summary>
			/// <param name="file"></param>
			/// <returns></returns>
		public static DataTable ExcelToTableForXLSX(string file)
		{
			DataTable dt = new DataTable();
			using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
			{
				NPOI.XSSF.UserModel.XSSFWorkbook xssfworkbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
				NPOI.SS.UserModel.ISheet sheet = xssfworkbook.GetSheetAt(0);

				//表頭  
				NPOI.SS.UserModel.IRow header = sheet.GetRow(sheet.FirstRowNum);
				List<int> columns = new List<int>();
				for (int i = 0; i < header.LastCellNum; i++)
				{
					object obj = GetValueTypeForXLSX(header.GetCell(i) as NPOI.XSSF.UserModel.XSSFCell);
					if (obj == null || obj.ToString() == string.Empty)
					{
						dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
						//continue;  
					}
					else
						dt.Columns.Add(new DataColumn(obj.ToString()));
					columns.Add(i);
				}
				//資料  
				for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
				{
					DataRow dr = dt.NewRow();
					bool hasValue = false;
					foreach (int j in columns)
					{
						dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as NPOI.XSSF.UserModel.XSSFCell);
						if (dr[j] != null && dr[j].ToString() != string.Empty)
						{
							hasValue = true;
						}
					}
					if (hasValue)
					{
						dt.Rows.Add(dr);
					}
				}
			}
			return dt;
		}

		/// <summary>  
		/// 獲取單元格型別(xlsx)  
		/// </summary>  
		/// <param name="cell"></param>  
		/// <returns></returns>  
		private static object GetValueTypeForXLSX(XSSFCell cell)
		{
			if (cell == null)
				return null;
			switch (cell.CellType)
			{
				case CellType.BLANK: //BLANK:  
					return null;
				case CellType.BOOLEAN: //BOOLEAN:  
					return cell.BooleanCellValue;
				case CellType.NUMERIC: //NUMERIC:  
					return cell.NumericCellValue;
				case CellType.STRING: //STRING:  
					return cell.StringCellValue;
				case CellType.ERROR: //ERROR:  
					return cell.ErrorCellValue;
				case CellType.FORMULA: //FORMULA:  
				default:
					return "=" + cell.CellFormula;
			}
		}

		/// <summary>  
		/// 將Excel檔案中的資料讀出到DataTable中(xls)  
		/// </summary>  
		/// <param name="file"></param>  
		/// <returns></returns>  
		public static DataTable ExcelToTableForXLS(string file)
		{
			DataTable dt = new DataTable();
			using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
			{
				HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
				ISheet sheet = hssfworkbook.GetSheetAt(0);

				//表頭  
				IRow header = sheet.GetRow(sheet.FirstRowNum);
				List<int> columns = new List<int>();
				for (int i = 0; i < header.LastCellNum; i++)
				{
					object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
					if (obj == null || obj.ToString() == string.Empty)
					{
						dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
						//continue;  
					}
					else
						dt.Columns.Add(new DataColumn(obj.ToString()));
					columns.Add(i);
				}
				//資料  
				for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
				{
					DataRow dr = dt.NewRow();
					bool hasValue = false;
					foreach (int j in columns)
					{
						dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
						if (dr[j] != null && dr[j].ToString() != string.Empty)
						{
							hasValue = true;
						}
					}
					if (hasValue)
					{
						dt.Rows.Add(dr);
					}
				}
			}
			return dt;
		}

		/// <summary>  
		/// 獲取單元格型別(xls)  
		/// </summary>  
		/// <param name="cell"></param>  
		/// <returns></returns>  
		private static object GetValueTypeForXLS(HSSFCell cell)
		{
			if (cell == null)
				return null;
			switch (cell.CellType)
			{
				case CellType.BLANK: //BLANK:  
					return null;
				case CellType.BOOLEAN: //BOOLEAN:  
					return cell.BooleanCellValue;
				case CellType.NUMERIC: //NUMERIC:  
					return cell.NumericCellValue;
				case CellType.STRING: //STRING:  
					return cell.StringCellValue;
				case CellType.ERROR: //ERROR:  
					return cell.ErrorCellValue;
				case CellType.FORMULA: //FORMULA:  
				default:
					return "=" + cell.CellFormula;
			}
		}

相關推薦

c#NPOI讀取excel 比interop和Microsoft.Jet.OLEDB.4.0 之類 的好的多

sage 整理 null workbook eric npoi EDA 構建 unknown 今天下午開始整理excel這塊, 微軟弄的那些庫簡直是個坑, 什麽com註冊之類的凈是些報錯. 在網上搜資料偶然碰見npoi ,好東西,值得使用 NPOI是指構建在POI 3.x版

C# NPOI讀取Excel資料

using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Wi

C#NPOI讀取Excel

/// <summary> /// 2007版Excel /// </summary> /// <param name="file"></param> /// <

C#使用NPOI讀取excel模板,並匯出excel

private void ExportDoctoryCase(HttpContext context) { //載入模板檔案路徑 string TempletFileName = context.Serv

C# 使用NPOI讀取Excel表格中第一個sheet中內容存在DataTable中

很久沒寫文章了,主要是從java轉到c#,經歷坎坷一言難盡呀,但最重的一點,就是變懶了。希望你們不要學小編。。。咳咳。。好乾貨開始。 二、前端用form表單提交即可,js或jq觸發form提交即可 <form class="form-hori

使用NPOI讀取Excel數據到DataTable

交換 tac sin 沒有 != region csharp edi XML 如今XML文件的存儲格式大行其道,可是也不是適用於全部情況,非常多單位的數據交換還是使用Excel的形式。這就使得我們須要讀取Excel內的數據。載入到程序中進行處理。可是如何有效率的讀取,如

NPOI 讀取Excel文件

tab con object ast file std error exceptio lean private void buttonExcel_Click(object sender, EventArgs e) {

NPOI讀取excel文件導出數據, 而此時文件正在打開中拋異常怎麽辦

post style xssf 使用 color 正在 tool blog xss 項目中需要用到一些數值表格, 方便起見都是用excel來的. 而如果excel正打開中, 直接使用npoi制作的工具來導出數據的話, 在這一行將會異常: workbook = new X

.net MVC使用NPOI讀取Excel模板,再寫入數據

produce clas actor 找到 讀取 粘貼 亮點 div gin   NPOI其實已經介紹的差不多了,再貼一個方便以後復制粘貼。 亮點其實是 Server.MapPath 這個東西,可以找到MVC工程下的文件夾,找路徑還是很方便的。 /// <su

NPOI 讀取Excel 表資料 資料裡面帶日期時的處理方法

將ExcelToDataTable 方法下的  //if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null // dataRow[j] = row.GetCell(j).ToString();  替換為 if (row.Ge

C#中讀取EXCEL檔案的第二種方法

using NPOI.HSSF.UserModel; using System; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace ReadExcel { class Program

WPF(二)——NPOI 讀取excel報錯

讀取07以前版本沒有問題,但讀取之後的版本會報錯。 錯誤型別: 原因: 程式集沒有或者版本沒有對上。 解決方案: (1)程式集沒有,下載對應版本dll並放到bin目錄,新增引用。 (

C#(.net)讀取excel資料 轉為datatable

#region 讀取Excel中的資料         /// <summary>          /// 讀取Excel中的資料 支援表頭(.xlsx)   不支援表頭(.xls) &

Java NPOI 讀取Excel 跳列 問題解決

讀取xls檔案的時候發現,比如表單一共3列(其中有些列沒有資料,空著的。如下圖: 當讀取到第2列的時候,就會自動跳過這一列。 問題程式碼: Row tRow = (Row) rows.ne

C#.net讀取Excel表中的資料時,有些欄位內容(字串、數字)讀取不到的解決辦法

匯入Excel時,會丟失一些手機號,或者固定電話號 問題出在於,他們將資料填入Excel時,有些格式是數值型別,有些是文字型別 當用OLEDB讀取Excel的時候,在Extended Properties中若沒有配置IMEX=1的屬性,微軟的處理機制是將列轉換為同一

NPOI讀取EXCEL到datagridview

/// <summary> /// 讀取Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param&g

新手小白用C# winform 讀取Excel

一、介面部分:首先,開啟visual studio新建專案;然後使用“工具箱”新增控制元件:分別新增button,datagridview,textbox三種窗體;所得到的介面圖如圖所示:(多加了幾個文字框)二、程式碼部分:1、新增名稱空間:using System.Data

C# OLEDB 讀取 Excel 記錄出現"標準表示式的型別不匹配"

使用OLEDB 進行 SELECT 操作時,出現 "標準表示式的型別不匹配" 的錯誤,原因是驅動解析 EXCEL 資料型別時,將文字識別為數字,導致 WHERE 子句中的條件欄位也給定的字元型別不匹配。 如:select top 1 * from [Sheet1$] whe

C# winform 讀取excel

namespace myTool { partial class Form1 { /// <summary> /// 必需的設計器變數。 /// </summary> pr

C#利用NPOI逐列讀取excel內容

C# NPOI 讀取excel using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS.UserModel; using NPOI.HSSF.U