write alreay opened excel usingc#

M

Makarand

hi

i want to write data in already opened excel file using C# code.

if anybody knows pls help me.

thnx in advance :)
 
M

Makarand

Already open by what?  Write data how?

You can modify an Excel file using the Office automation API.  But to make  
changes to the file on disk, you have to have write permissions, and if  
the file has already been opened somewhere else, unless it was opened  
read-only by that "somewhere else", you don't have write permissions.

Pete

thnx for reply.

but my scenario is like this.

i have opened excel file by click.

then i want to write the same opened excel file using c# code.

currently i can write the file by creating excel object but then the
written data is not being refetecd in already opened file untill we
close file and reopen it.

i want data to be reflected in excel as soon as i write from code
 
A

AA2e72E

This is a simple solution without any error trapping etc.

In your C# project,

1. Add
using System.Runtime.InteropServices;
2. Add areference to
Microsoft Excel nn.n Object Library
where nn.n is a version number e.g. 1.0 for Excel/XP etc.
3. Now you can get hold of the open Excel session as follows:
Excel.Application xlObj =
(Excel.Application)Marshal.GetActiveObject("Excel.Application");

WARNINGS:

1. This will fail if there is no existing session of Excel.
2. You will always get the oldest session if multiple Excel sessions exist.

It might be wise to:

private void button3_Click(object sender, EventArgs e)
{
Excel.Application xlObj =
(Excel.Application)Marshal.GetActiveObject("Excel.Application");
MessageBox.Show(xlObj.ActiveCell.Value2.ToString());
}

1. Set the UserControl property of xlObj to false
2. Then, to set the visible property to false (to avoid conflicts between
the automation and interactive sessions which are one and the same thing).

To Test:
1. Create a new session of Excel
2. Add a button to a form in a Windows Application project , say button3
3. Type something in cell A1 of Excel & ensure that the cursor is in cell A1
afterwards.

Run the application and then Click the button (for whose click event you
will have added) the following code:

PS: C# is extremely hardwork when working with Excel because it does not
support optional arguments (as VB.NET does) and overloading in this context
creates clutter (I think).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top