using System; using System.Collections.Generic; using System.Text; // ref https://www.c-sharpcorner.com/article/read-excel-file-in-c-sharp-winform/ //using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Data; using Microsoft.Office.Interop; namespace solarApp.Service { public class excelHelper { void readExcel(string fname, ref System.Data.DataTable dt) { Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fname); Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; DataRow mydr; // dt.Column = colCount; //dataGridView1.ColumnCount = colCount; //dataGridView1.RowCount = rowCount; for (int i = 1; i <= rowCount; i++) { mydr = dt.NewRow(); for (int j = 1; j <= colCount; j++) { //write the value to the Grid if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) { //dataGridView1.Rows[i - 1].Cells[j - 1].Value = xlRange.Cells[i, j].Value2.ToString(); } // Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); //add useful things here! } } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //rule of thumb for releasing com objects: // never use two dots, all COM objects must be referenced and released individually // ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); } //public void ReadSample() //{ // Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); // if (excelApp != null) // { // Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\test.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); // Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.Sheets[1]; // Excel.Range excelRange = excelWorksheet.UsedRange; // int rowCount = excelRange.Rows.Count; // int colCount = excelRange.Columns.Count; // for (int i = 1; i <= rowCount; i++) // { // for (int j = 1; j <= colCount; j++) // { // Excel.Range range = (excelWorksheet.Cells[i, 1] as Excel.Range); // string cellValue = range.Value.ToString(); // //do anything // } // } // excelWorkbook.Close(); // excelApp.Quit(); // } //} } }