最近因爲工作需要讀取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 . . .