Skip to content

Instantly share code, notes, and snippets.

@bozhink
Last active June 6, 2017 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bozhink/2ad1b691e4acbe3817a30fa66415361c to your computer and use it in GitHub Desktop.
Save bozhink/2ad1b691e4acbe3817a30fa66415361c to your computer and use it in GitHub Desktop.
Read data from MS Excel
/// <summary>
/// See https://coderwall.com/p/app3ya/read-excel-file-in-c
/// </summary>
namespace App
{
using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel; //microsoft Excel 14 object in references-> COM tab
public class Program
{
public static void Main(string[] args)
{
if (args.Length > 0)
{
GetExcelFile(args[0]);
}
}
public static void GetExcelFile(string fileName)
{
//Create COM Objects. Create a COM object for everything that is referenced
Excel.Application excelApplication = new Excel.Application();
Excel.Workbook excelWorkbook = excelApplication.Workbooks.Open(fileName);
Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
//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 = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
{
Console.Write("\r\n");
}
var cell = excelRange.Cells[i, j];
//write the value to the console
if (cell != null && cell.Value2 != null)
{
Console.Write(cell.Value2.ToString() + "\t");
////if (j == 4)
////{
//// cell.Value2 += 1;
////}
}
}
}
////excelWorkbook.Save();
//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(excelRange);
Marshal.ReleaseComObject(excelWorksheet);
//close and release
excelWorkbook.Close();
Marshal.ReleaseComObject(excelWorkbook);
//quit and release
excelApplication.Quit();
Marshal.ReleaseComObject(excelApplication);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment