最近因为工作需要读取excel数据进行分析,对c#读取excel进行了学习,总结一下,方便以后查找。
下面的类具备打开当前文件夹下指定名字的excel文件,读取指定单元格内容,关闭excel文件的功能。
需要添加对Microsoft.Office.Interop.Excel组件的引用,代码如下:
using Microsoft.Office.Interop.Excel;
using System;
using System.IO;
using System.Reflection;
class MyExcel
{
private Microsoft.Office.Interop.Excel.Application xls; //声明excel应用程序对象
private _Workbook book; //声明workbook对象
private string Excelfilename = null; //workbook文件名
public bool OpenBook() //打开Excel文件
{
string Current = Directory.GetCurrentDirectory();//获取当前目录
if (Excelfilename == null)
return false;
else
Excelfilename = Current + @"\" +Excelfilename;
this.xls = new Microsoft.Office.Interop.Excel.Application();//实例化excel对象
try//判断文件是否打开
{
this.book = xls.Workbooks.Open(Excelfilename, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
catch
{
Console.WriteLine("打开文件" + Excelfilename + "失败!!");
Console.Read();
return false;
}
if (book.ReadOnly)//判断文件是否被占用
{
book = null;
xls.Quit();
GC.Collect();
Console.WriteLine(Excelfilename + "文件已打开,请关闭后重试。");
return false;
}
xls.Visible = false;//设置Excel后台运行
xls.DisplayAlerts = false;//设置不显示确认修改提示
return true;
}
public void CloseBook()
{
book.Close(false, Missing.Value, Missing.Value);//关闭打开的表
xls.Quit();//Excel程序退出
GC.Collect();//系统回收资源
}
public MyExcel(string filename)
{
Excelfilename=filename;
}
public string GetString(string SheetName, int row,int column)
{
_Worksheet sheet = (_Worksheet)book.Worksheets.get_Item(1);//定义sheet变量
for (int i = 1; i < book.Worksheets.Count; i++)
{
sheet = (_Worksheet)book.Worksheets.get_Item(i);//获得第i个sheet
if (sheet.Name == SheetName)//判断sheet的名字是否为SheetName
break;
}
return sheet.Cells [row, column].Text;
}
}
写了一个测试函数,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test1
{
class Program
{
static void Main(string[] args)
{
MyExcel excelbook = new MyExcel("test.xlsx");
excelbook.OpenBook();
for (int row = 1; row < 10; row++)
Console.WriteLine(excelbook.GetString("Sheet1", row, 1) + "," + excelbook.GetString("Sheet1", row, 2));
excelbook.CloseBook();
}
}
}
test.xlsx文件中的内容如下:
在VS2013中运行结果如下:
1,1
2,8
3,27
4,64
5,125
6,216
7,343
8,512
9,729
Press any key to continue . . .