Link to home
Start Free TrialLog in
Avatar of Gani tpt
Gani tpt

asked on

C# - How to write data in selected cell from datatable.

Hi,

I am using datatable and it contains some values.

i want tp write those values in excel file which is already contain some data in sheet1.

so my output would print in where i mentioned the cell.

for example,

my datatable should write starting cell in C12.

so the datatable should write from there. (see sample output image attached).

EmpNo      Name      Dept      Place
101      John      MATHS      USA
102      Robert      PHYSICS      INDIA
103      Anu      ENGLISH      CHINA

output image.(PFA)

How to write datatable value in c#..?
Output_Excel.png
Avatar of Norie
Norie

Is it the entire datatable, including headers, you want to write to Excel?
Please review this on general interop features from C#:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interop/how-to-access-office-onterop-objects

 var excelApp = new Excel.Application();
  excelApp.Visible = true;
excelApp.Workbooks.Open(@"C:\test.xlsx");
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
workSheet.Cells[12, "C"] = "Test";

Open in new window


You should be able to copy the data to the cells from there using different columns / offsets.  Let me know if you need more help.

Note the above starts a new application of excel.  If you're excel is already opened you can use the following (from https://stackoverflow.com/questions/1118735/get-instance-of-excel-application-with-c-sharp-by-handle):

public Excel.Application StartExcel()
{
    Excel.Application instance = null;
    try
    {
       instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch (System.Runtime.InteropServices.COMException ex)
    {
       instance = new Excel.Application();
    }

    return instance;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gani tpt

ASKER

Excellent solution..
User generated imageHow to set border for each  cell (for all the records from data table).

for example,

i want to print all the cell with border at all the records including header. (with header font is bold).
Can you start a new question for that?
ok.thanks...