Tip #1 - Reading from Excel
Please find below template excel with columns and data listed below. Objective to read all the worksheets and display data available in individual sheets
You need to use namespace Microsoft.Office.Interop.Excel.
Console Application in C# provided below (.NET 4.0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelPOCDemo
{
public class Program
{
static void Main(string[] args)
{
Program P = new Program();
P.LoadDataFromExcel();
}
public string
LoadDataFromExcel()
{
try
{
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook xlWorkbook =
ExcelApp.Workbooks.Open("E:\\Book1.xlsx");
foreach (Excel.Worksheet
Sheet in xlWorkbook.Worksheets)
{
Console.WriteLine(" WorkSheet
Name is " + Sheet.Name);
Excel.Range DataRange = Sheet.UsedRange;
int rowCount = DataRange.Rows.Count;
int colCount = DataRange.Columns.Count;
for (int i = 1; i <= rowCount;
i++)
{
for(int j = 1;
j<=colCount; j++)
{
Console.WriteLine("Value
of i is " + i + " Value of J is
" + j + " Data is " +
DataRange.Cells[i, j].Value2.ToString());
}
}
}
ExcelApp.Workbooks.Close();
ExcelApp.Quit();
Console.ReadLine();
return "0";
}
catch(Exception
Ex)
{
return "-1";
}
}
}
}
Tip #2 - Implementing optional parameters for method calls. Current code is implemented without any method parameter. For a new change I need to pass a method parameters. To support optional parameter implementation please find below example. C# 4.0 example, using namespace System.Runtime.InteropServices, Optional Keyword and Default Value. Simple C# Console Application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace OptionalParameters
{
public class Program
{
static void Main(string[] args)
{
Program P = new Program();
P.method();
P.method("A");
Console.ReadLine();
}
public void method([Optional, DefaultParameterValue(null)] string
ParameterA)
{
if (ParameterA != null)
{
Console.WriteLine("Parameter sent is " +
ParameterA.ToString());
}
else
{
Console.WriteLine("Parameter sent is null");
}
}
}
}
Output result is
Tip #4 - Converting a list to a array. How to convert a list to an array
Sample List demo and Array Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListArrayExample
{
public class Program
{
static void Main(string[] args)
{
List<string>
ElementList = new List<string>();
ElementList.Add("ElementA");
ElementList.Add("ElementB");
ElementList.Add("ElementC");
ElementList.Add("ElementD");
Elements = ElementList.ToArray();
foreach (String
Data in Elements)
{
Console.WriteLine("Value is " + Data);
}
Console.ReadLine();
}
}
}
Output Result is
Tip #5 - Clearing elements from an array. Thanks to this post for letting me know on Array.clear method to clear data present in array
Happy Learning!!!
No comments:
Post a Comment