C#使用Microsoft.Office.Interop.Excel读取数据

我有一个数据表,我需要从Excel中读取基于用户input,并将其存储在VS作为一个数组。

如果用户inputC1,则search并获取关联的数据:

数组[0]:X1E1M101

arrays[1]:F2G1M202

如果用户inputC2:

数组[0]:X1E1M105

数组[1]:F1G2M304


我的资料:

ABCDE 1 C1 2 3 X1 E1 M1 01 4 F2 G1 M2 02 5 6 C2 7 8 X1 E1 M1 05 9 F1 G2 M3 04 10 

我的代码:

 //I declared the Interop using Excel = Microsoft.Office.Interop.Excel; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range range; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(ManufacturingFile); //xlWorkSheet = ("Default Value"); // i get an error here when trying to define the worksheet name i want to select. "Cannot impicitly convert type string to ... excel.worksheet' xlWorkSheet = ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Select(); // This method also I get an error. xlWorkSheet.Activate(); 

我被困在这部分之后,因为我是使用Interop的新手。 希望有人能帮助我,我是C#的初学者,非常感谢您的帮助。

你将不得不打开你的woorkbook和工作表,有一些例子解释如何做到这一点,这里是一个例子

  Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range range; string str; int rCnt = 0; int cCnt = 0; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open("testone.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); range = xlWorkSheet.UsedRange; Microsoft.Office.Interop.Excel.Range xlFound =range.EntireRow.Find("C2",misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,true, misValue, misValue); if (!(xlFound == null)) { int ID_Number = xlFound.Column; int rownum = xlFound.Row; Console.WriteLine(ID_Number); Console.WriteLine(rownum); Console.Read(); } 

你可以首先得到search的范围值,例如,如果'C1'在a1处,你将必须从(n + 2)中读取整行,并在find空行时停止。

上面的代码不是从这里编译的

如果你只是从excel文件读取数据,我build议你使用ExcelDataReader库,它提供了更好的性能,不会离开幽灵进程,而不是互操作。 这里有一些示例代码来设置你:

  IExcelDataReader reader = null; string FilePath = "PathToExcelFile"; //Load file into a stream FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read); //Must check file extension to adjust the reader to the excel file type if (System.IO.Path.GetExtension(FilePath).Equals(".xls")) { reader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (System.IO.Path.GetExtension(FilePath).Equals(".xlsx")) { reader = ExcelReaderFactory.CreateBinaryReader(stream); } if (reader != null) { //Fill DataSet System.Data.DataSet result = reader.AsDataSet(); try { //Loop through rows for the desired worksheet //In this case I use the table index "0" to pick the first worksheet in the workbook foreach (DataRow row in result.Tables[0].Rows) { string FirstColumn = row[0].ToString(); } } catch { } }