How to read from and write to excel sheet with C#:
How to read from and write to excel sheet with C#:
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//Create application object
_Application docXL = new Microsoft.Office.Interop.Excel.Application();
//Create workbook object
_Workbook workbookXL = docXL.Workbooks.Open(@"C:\temp\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//create worksheet object
_Worksheet worksheetXL = (_Worksheet)workbookXL.ActiveSheet;
//Write to the cells based on the range values
((Range)worksheetXL.Cells["1", "A"]).Value2 = "aa";
((Range)worksheetXL.Cells["1", "B"]).Value2 = "bb";
//Read from cells based on rane vales
Console.WriteLine(((Range)worksheetXL.Cells["1", "B"]).Value2);
//house-keeping code
workbookXL.Save();
workbookXL.Close(false, Type.Missing, Type.Missing);
docXL.Application.DisplayAlerts = true;
docXL.Application.Quit();
Console.ReadKey();
}
}
}
Please add your comments if it helps....
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//Create application object
_Application docXL = new Microsoft.Office.Interop.Excel.Application();
//Create workbook object
_Workbook workbookXL = docXL.Workbooks.Open(@"C:\temp\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//create worksheet object
_Worksheet worksheetXL = (_Worksheet)workbookXL.ActiveSheet;
//Write to the cells based on the range values
((Range)worksheetXL.Cells["1", "A"]).Value2 = "aa";
((Range)worksheetXL.Cells["1", "B"]).Value2 = "bb";
//Read from cells based on rane vales
Console.WriteLine(((Range)worksheetXL.Cells["1", "B"]).Value2);
//house-keeping code
workbookXL.Save();
workbookXL.Close(false, Type.Missing, Type.Missing);
docXL.Application.DisplayAlerts = true;
docXL.Application.Quit();
Console.ReadKey();
}
}
}
Comments
Post a Comment