C# NPOI 讀取excel 全部資料

 
 
try
{
	IWorkbook workbook;
	//讀取專案內中的sample.xls 的excel 檔案
	string FilePath = FileList.FilePath;
	using (FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
	{
		workbook = WorkbookFactory.Create(file);
	}
	List<Models.OldOwnerList> OldOwnerLists = new List<Models.OldOwnerList>();
	for (int si = 0; si < workbook.NumberOfSheets; si++)
	{

		//讀取Sheet1 工作表
		var sheet = workbook.GetSheetAt(si);

		List<Dictionary<int, string>> dataList = new List<Dictionary<int, string>>();
		for (int row = 0; row <= sheet.LastRowNum; row++)
		{
			try
			{

				if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
				{
					Dictionary<int, string> data = new Dictionary<int, string>();
					IRow ss = sheet.GetRow(row);
					foreach (var c in ss)
					{
						NPOI.SS.Util.CellAddress CellAddress = c.Address;
						string str = "";

						if (c.CellType == CellType.Numeric || c.CellType == CellType.Formula)
						{
							try
							{
								Console.Write(c.NumericCellValue.ToString("#"));
								str = c.NumericCellValue.ToString().Trim();
							}
							catch (Exception)
							{
								str = "錯誤";
							}
						}
						else if (c.CellType == CellType.String)
						{
							Console.Write(c.StringCellValue);
							str = c.StringCellValue.Trim();
						}
						else if (c.CellType == CellType.Blank)
						{
							Console.Write(c.StringCellValue);
							str = c.StringCellValue.Trim();

						}
						else if (c.CellType != CellType.Error)
						{

							Console.Write(c.StringCellValue);
							str = c.StringCellValue.Trim();
						}
						else
						{

						}
						data.Add(CellAddress.Column, str);
					} 
					dataList.Add(data);
				}
				else
				{

				}
			}
			catch (Exception mm)
			{

				throw;
			}
		}
		if (dataList.Count() > 0)
		{

			foreach (var iii in dataList.Skip(1))
			{
				foreach (var d in dataList[0])
				{
					if (!iii.ContainsKey(d.Key))
					{
						iii.Add(d.Key, "");
					}
				}
			} 
		}

}
catch (Exception mm)
{
	ApiReturn.Message = "匯入失敗," + mm.Message;
	ApiReturn.Code = 0;
} 
分類: C#