近期有需求要用C#來讀Excel裏的數據。上網查到了,爲了以後查詢方便,所以在此做個C#連接Excel小結。
步驟如下:
1、EXCEL.DLL 製作
首先需要在自己Office文件目錄拿到EXCEL.EXE文件。
我自己EXCEL版本爲2016,所以在C:\Program Files\Microsoft Office\Office16\EXCEL.EXE。自己可以在自己office安裝目錄下面去找,很容易找到。
進一步打開VS2013(或者其他版本同理)在VS的文件目錄下找到visual Studio2013 命令提示工具,通過命令提示定位到EXCEL.EXE所在地,再利用運行“tlbimp Excel.EXE Excel.dll”的命令,將EXCEL.EXE文件編譯爲Excel.dll文件。通過以上操作可以較爲快速得到EXCEL.DLL文件。
2、添加引用
在C#中添加引用,導入自己編譯生成的EXCEL.DLL文件。並在擡頭編寫using Microsoft.Office.Interop.Excel;
3、寫代碼測試
先放圖如下:
代碼如下:
System.Diagnostics.Stopwatch watchtime = new Stopwatch();
watchtime.Start();
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//將新值賦給一個數組
if (excel == null)
{
MessageBox.Show("Can't create excel!");
}
else
{
excel.Visible = false; excel.UserControl = true;
Workbook wb = excel.Application.Workbooks.Open(ExcelFileName, missing, true, missing, missing, missing
, missing, missing, missing, true, missing, missing, missing, missing, missing);
//取得第一個工作薄
Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
//取得總記錄行數 (包括標題列)int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行數
int columnsint = ws.UsedRange.Cells.Columns.Count;//得到列數
//獲得點個數SpaceRendezvousN = rowsint - 1;
//取得數據範圍區域 (不包括標題列)
Range exceldata;
string currentstr = "";
currentstr += (char)('A' + columnsint - 1);
exceldata = ws.Cells.get_Range('A' + "2", currentstr + "2" + rowsint);
object[,] arryItem = (object[,])exceldata.Value2; //get range's value
for (int i = 0; i < rowsint - 1; i++)
{
//增加一個點位
int index = this.dataGridView1.Rows.Add();
SpaceRendezvous_OriData Space_rendezvous_data = new SpaceRendezvous_OriData();
for (int j = 0; j < columnsint; j++)
{
//Item_Code列
this.dataGridView1.Rows[i].Cells[j].Value = (arryItem[i + 1, j + 1]).ToString();
}
Space_rendezvous_data.Num = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[0].Value);
Space_rendezvous_data.gcpX = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[1].Value);
Space_rendezvous_data.gcpY = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[2].Value);
Space_rendezvous_data.gcpZ = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[3].Value);
Space_rendezvous_data.x = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[4].Value);
Space_rendezvous_data.y = Convert.ToDouble(this.dataGridView1.Rows[i].Cells[5].Value);
SpaceRendezvous_ControlPoints.Add(Space_rendezvous_data);
}
}
watchtime.Stop();
TimeSpan timespan = watchtime.Elapsed;
excel.Quit();
excel = null;
上面代碼標紅的地方就是讀取Excel數據的過程,有註釋很容易看懂。值得注意的是最後excel.Quit()和excel = null;需要加上去,不然的話,你的內存會被你所創建的excel文件所塞滿。