C#提取Excel表格数据至数据结构对象

定义数据结构

    public class Info
    {
        public string Info1 { get; set; } = string.Empty;

        public string Info2 { get; set; } = string.Empty;

        public string Info3 { get; set; } = string.Empty;

        public string Info4 { get; set; } = string.Empty;
    }

获取数据结构

public void GetInfo(string FilePath)
{
	Excel.Application excelApp = null;
	Excel.Workbook workbook = null;
	Excel.Worksheet worksheet = null;

	try
	{    
		string FileName = string.Empty;
		FileName = Path.GetFileNameWithoutExtension(FilePath);
		excelApp = new Excel.Application();
		workbook = excelApp.Workbooks.Open(FilePath);
		worksheet = workbook.Worksheets["Sheet1"]; // 第一个工作表
		int rowCount = worksheet.UsedRange.Rows.Count;
		for (int row = 2; row <= rowCount; row++) // 假设第一行为标题
		{
			Info tmp = new Info();

			tmp.Info1 = worksheet.Cells[row, 1].Text;
			tmp.Info2 = worksheet.Cells[row, 2].Text;
			tmp.Info3 = worksheet.Cells[row, 3].Text;
			tmp.Info4 = worksheet.Cells[row, 4].Text;   
		}
	}
	finally
	{
		// 确保释放 COM 对象
		if (worksheet != null) Marshal.ReleaseComObject(worksheet);
		if (workbook != null)
		{
			workbook.Close();
			Marshal.ReleaseComObject(workbook);
		}
		if (excelApp != null)
		{
			excelApp.Quit();
			Marshal.ReleaseComObject(excelApp);
		}
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值