C#在select语句中引用Excel Worksheet索引

时间:2015-01-06 17:05:17

标签: c# excel

任务:     我需要使用C#将Excel电子表格工作表的内容加载到datagridview中。

进度:     我通过OLEdbConnection连接到Excel电子表格,我需要在select语句中通过工作表索引引用第一个工作表。 (我不知道工作表的名称是什么,但我们总是会加载第一个工作表。)下面是我到目前为止的代码......


tbFileName.Text = openFileDialog1.FileName;

System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tbFileName.Text + ";Extended Properties=Excel 12.0;");
//MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [FlexAccountView$]", MyConnection); <-- accessing worksheet by name...

**MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from " + [need worksheet index reference here], MyConnection);**

我知道这很容易,但由于某些原因,我今天画了一个空白。我已经搜索过了,但我们还没有找到我想要的东西。任何帮助将不胜感激。谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

这可能不是最好的方法,但这是我能够从Sorceri提供的链接中提取的..

OleDbConnection MyConnection;
DataSet DtSet;
OleDbDataAdapter MyCommand;
MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tbFileName.Text + ";Extended Properties=Excel 12.0;");

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 

//get the workbook
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(tbFileName.Text); 

//get the first worksheet
Microsoft.Office.Interop.Excel.Worksheet wSheet = excelBook.Sheets.Item[1]; 

//reference the name of the worksheet from the identified spreadsheet item
MyCommand = new OleDbDataAdapter("select * from [" + wSheet.Name + "$]", MyConnection);

希望这有助于某人更快地找到它。

答案 1 :(得分:0)

按索引选择工作表的最简单方法是......

Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook WorkBook = ExcelApp.Workbooks.Open(inputFile);
Excel.Worksheet WorkSheet = WorkBook.Worksheets[1]; // This is the simplest call