Photo Gallery

Thursday, February 22, 2018

How to Read and Write Excel file ? Update specific cell using C#

In this tutorial , i will explained how to Read and Write (insert) data to Excel file Sheet in ASP.Net using C#.

The data will be update using ( System.Runtime.InteropServices ) library based on supplied input argument.

let's have a look,

This is our excel file, as you can see first column is Name and Second column is Designation, if you want to update the Designation column for specific name then follow the steps below..






Step 1 : Open Visual studio and create the New Project as Console Application




Step 2 : Add Microsoft.Office.Interop.Excel library using Nuget Package Manager.





Step 3 : Add below code in your program.cs file and you are done.

public class Program
{
static void Main(string[] args)
{
string name = "Chintan";
string designation = "Consultant";
ReadAndUpdateExcel(name, designation);
}
private static void ReadAndUpdateExcel(string name, string designation)
{
string filePath = @"C:\TEMP\ReadWriteExcelTest\Employee.xls";
Application xlApp = new Application();
xlApp.DisplayAlerts = false;
xlApp.Interactive = false;
xlApp.ScreenUpdating = false;
xlApp.Visible = false;
xlApp.UserControl = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, 0, Editable: true);
Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Range xlRange = xlWorksheet.UsedRange.Columns[1, Type.Missing].Rows;
object _missingValue = System.Reflection.Missing.Value;
Range found = xlRange.Find(name, _missingValue, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByColumns, XlSearchDirection.xlNext, true, _missingValue, _missingValue);
if (found != null)
{
Range matchedCell = xlWorksheet.Rows.Cells[found.Row, 2];
matchedCell.Value = designation;
xlWorkbook.Save();
}
// cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
// 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);
Console.WriteLine("File Updated Succesfully");
Console.ReadLine();
}
}
Step 4 : Execute the program and see the results as expected.




Step 5 : You are done.




If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below.


Thank you !!!

No comments:

Post a Comment