mkilkelly
8/14/2017 - 8:12 PM

Read Excel file

Read Excel file

private List<string[]> getDataFromExcel(string excelFile, int numCols, int worksheetNum) {
	// open Excel and read data
	Excel.Application excelApp = new Excel.Application();
	Excel.Workbook excelWb = excelApp.Workbooks.Open(excelFile);
	Excel.Worksheet excelWs = (Excel.Worksheet)excelApp.Worksheets.Item[worksheetNum];
	Excel.Range excelRng = (Excel.Range)excelWs.UsedRange;
		
	// get row count
	int rowCount = excelRng.Rows.Count;
		
	// create list for sheet data
	List<string[]> dataList = new List<string[]>();
		
	// loop through Excel data and put into data structure
	for(int i = 1; i <= rowCount; i++) {
		// create array for row data
		string[] sheetData = new String[numCols];
			
		// loop through columns and output data to array
		for(int j = 1; j <= numCols; j++) {
			// get Excel data
			Excel.Range cellData = (Excel.Range)excelWs.Cells[i,j];

			// add data to array
			sheetData[j-1] = cellData.Value2.ToString();
		}

		// add sheet data to list
		dataList.Add(sheetData);
	}

	// close Excel and cleanup
	excelWb.Close();
	excelApp.Quit();
	System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
	System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWb);
	System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWs);
	System.Runtime.InteropServices.Marshal.ReleaseComObject(excelRng);

	// return list
	return dataList;
}