asked on
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace CrapNetCore
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string WorkBook = @"C:\Temp\ExcaelFile.xls";
if (File.Exists(WorkBook))
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(WorkBook);
Excel._Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets[3];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = 8;// xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
int PrefCount = 1;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 3; i <= rowCount; i++)
{
string ColA = xlRange.Cells[i, 1].ToString();
Console.WriteLine("Value of CollA {0}", ColA);
}
Console.ReadLine();
//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);
}
}
}
}