C# 解析Excel

分享一篇自己写的 解析Excel的代码
网上很多帖子都写的太复杂了,就自己重新整理了一份
支持读写

Microsoft.Office.Interop.Excel
这个是个DLL 直接百度下载就可以了。
添加进解决方案的引用

using Microsoft.Office.Interop.Excel;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace JpWordCheckForTTL
{
	class ExcelHelper
	{
		private string m_strPath = null;    // 打开的Excel路径 or 需要创建的excel路径;
		private bool m_isCreateMode = false;
		private object MISSING_VALUE = System.Reflection.Missing.Value;

		private Application m_AppMain = null;
		private Workbook m_Workbook = null;
		private Worksheet m_Worksheet = null;

		/// <summary>
		/// 创建一个解析器;
		/// </summary>
		public static ExcelHelper CreateExcelHelper()
		{
			Application appMain = new Application();
			if (appMain == null)
			{
				return null;
			}
			appMain.Visible = false;
			appMain.UserControl = true;

			ExcelHelper eh = new ExcelHelper();
			eh.m_AppMain = appMain;
			return eh;
		}

		public bool CreateExcel(string strPath)
		{
			m_strPath = strPath;
			m_isCreateMode = true;
			//新建一张表;
			m_Workbook = m_AppMain.Workbooks.Add(MISSING_VALUE);
			return true;
		}

		public bool OpenExcel(string strPath)
		{
			m_isCreateMode = true;
			try
			{
				m_Workbook = m_AppMain.Workbooks.Open(strPath);
				if (m_Workbook == null)
				{
					MessageBox.Show("OpenExcel Error, m_Workbook is null");
					return false;
				}
				return true;
			}
			catch(Exception e)
			{
				MessageBox.Show("OpenExcel Error, Message : " + e.Message);
				return false;
			}
		}

		public int RowCount
		{
			get
			{
				return m_Worksheet.UsedRange.Cells.Rows.Count; //得到行数
			}
		}

		public int ColCount
		{
			get
			{
				return m_Worksheet.UsedRange.Cells.Columns.Count;//得到列数
			}
		}
		
		/// <summary>
		/// 选择一个页,BeginIndex == 1
		/// </summary>
		public void SelectPage(int nPageIndex = 1)
		{
			//取得第一个工作薄
			m_Worksheet = (Worksheet)m_Workbook.Worksheets.get_Item(nPageIndex);
		}

		public string ReadGrid(int nRow,int nCol)
		{
			Range range = m_Worksheet.Cells[nRow, nCol];
			return (string)range.Text;
		}

		public void WriteGrid(int nRow, int nCol, string strValue)
		{
			m_Worksheet.Cells[nRow, nCol] = strValue;
		}

		public void Save()
		{
			if (m_isCreateMode)
			{
				m_Workbook.SaveAs(m_strPath);
			}
			else
			{
				MessageBox.Show("Not Create Mode, Can not call Function:Save to use.");
			}
		}

		public void Close()
		{
			m_Workbook.Close(true);
			m_AppMain.Quit();
			Kill(m_AppMain);//调用kill当前excel进程  
		}


		[DllImport("User32.dll")]
		public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int Processid);

		public static void Kill(Microsoft.Office.Interop.Excel.Application theApp)
		{
			int iId = 0;
			IntPtr intptr = new IntPtr(theApp.Hwnd);
			System.Diagnostics.Process p = null;

			try
			{
				GetWindowThreadProcessId(intptr, out iId);
				p = System.Diagnostics.Process.GetProcessById(iId);

				if (p != null)
				{
					p.Kill();
					p.Dispose();
				}
			}
			catch (Exception e)
			{
				throw e;
			}
		}
	}
}

Demo:

			//Excel的下标是从 1行 1列 开始的;
			ExcelHelper excelWrite = ExcelHelper.CreateExcelHelper();
			excelWrite.CreateExcel(@"C:\MyWorks\test.xlsx");
			excelWrite.SelectPage(1);
			excelWrite.WriteGrid(1, 1, "test11");
			excelWrite.WriteGrid(1, 2, "test12");
			excelWrite.WriteGrid(2, 1, "test21");
			excelWrite.WriteGrid(2, 2, "test22");
			excelWrite.Save();
			excelWrite.Close();

			ExcelHelper excelRead = ExcelHelper.CreateExcelHelper();
			excelRead.OpenExcel(@"C:\MyWorks\test.xlsx");
			excelRead.SelectPage(1);
			string str1 = excelRead.ReadGrid(1, 1);
			string str2 = excelRead.ReadGrid(1, 2);
			string str3 = excelRead.ReadGrid(2, 1);
			string str4 = excelRead.ReadGrid(2, 2);
			excelRead.Close();
			//Excel是后台进程处理,不close,进程会一直挂在那里。之后的IO操作会有问题;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值