Click here to Skip to main content
12,501,845 members (52,985 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#
how to write text box values to an excel sheet using c#?i want to enter those data to cells by selecting them.please help me.
Posted 25-Feb-13 2:36am
Comments
Jegan Thiyagesan 25-Feb-13 8:47am
   
What have you searched for?
What have you tried?
Where did you get stuck?
muthuu 25-Feb-13 8:52am
   
i have to access excel data and update some cells of it using c# code. i did first part and it went succesful. but i'm stucked in second part of write to cell.how can i write values of a text box to a cell.that's where i stucked.
Jegan Thiyagesan 25-Feb-13 9:02am
   
Can you post the code that you are writing to the Cell?
muthuu 25-Feb-13 9:27am
   
Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
Excel.Workbook workbook = (Excel.Workbook)excelApp.Workbooks.Add(Missing.Value);
Excel.Worksheet worksheet;

worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

((Excel.Range)worksheet.Cells["1", "A"]).Value2 = "5";
((Excel.Range)worksheet.Cells["2", "A"]).Value2 = "7";

//in first line they are saying an error "application class can't be embedded"
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

hi,

Can you try this:
First you must import "Microsoft.Office.Core" and "Microsoft.Office.Interop.Excel" COM references.

Second:
public void WriteToExcel()
{
   string myPath = @"C:\Excel.xls"; // this must be full path.
   FileInfo fi = new FileInfo(myPath);
   if (!fi.Exists)
   {
       Console.Out.WriteLine("file doesn't exists!");
   }
   else
   {
        var excelApp = new Microsoft.Office.Interop.Excel.Application();
        var workbook = excelApp.Workbooks.Open(myPath);
        Worksheet worksheet = workbook.ActiveSheet as Worksheet; 
 

        Microsoft.Office.Interop.Excel.Range range = worksheet.Cells[1,1] as Range;
        range.Value2 = "5";
 
        //excelApp.Visible = true;
        workbook.Save();
        workbook.Close();
   }
}

I hope this helps.

Regards
Jegan
  Permalink  
Comments
muthuu 25-Feb-13 21:48pm
   
Thank you for your help.i will try this.
muthuu 27-Feb-13 0:20am
   
I tried this code..but it gives following error for " Microsoft.Office.Interop.Excel.Range range = worksheet.Cells[1,1] as Range;"
this line..
nullreferenceunhandled..
can you please tell me a solution for that?
Jegan Thiyagesan 27-Feb-13 4:49am
   
Means your worksheet is null, means your workbook is null.
Did you give the full path to open the excel file? i.e. C:\blalba\blabla\blabla\Excel.xls.

Jegan
muthuu 28-Feb-13 0:20am
   
now it works..but there is another problem when i use this method to write several data to same excel.i want to add several data to a same excel which is exsiting.but when i tried it it always open excel sheet foe each time when i call this method..is there any method to close the excel like excel.close or something?
muthuu 28-Feb-13 0:24am
   
public void WriteToExcel(string myPath,string row,string col,string val)
{

FileInfo fi = new FileInfo(myPath);
if (!fi.Exists)
{
MessageBox.Show("file doesn't exists!");
}
else
{
var excelApp = new Microsoft.Office.Interop.Excel.Application();
var workbook = excelApp.Workbooks.Open(myPath);


Excel.Worksheet worksheet;

worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

((Excel.Range)worksheet.Cells[row, col]).Value2 = val;

excelApp.Visible = true;





//workbook.Save();
workbook.Close();


}
}
muthuu 28-Feb-13 0:25am
   
above is the method which iam using..by giving those 4 parameters i want to add data.how can i do that to same excel without opening again and again?
Jegan Thiyagesan 1-Mar-13 3:53am
   
Hi, you open the file only once, then you iterate through the cells to add values into cells.
so you will have a for loop like this below:

for (int row = 0; row < rowCount; ++row)
{
for (int col = 0; col < columnCount; ++col)
{
((Excel.Range)worksheet.Cells[row, col]).Value2 = val;
}
}

Regards
Jegan
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

  Permalink  
Comments
muthuu 25-Feb-13 21:49pm
   
Thank you for your help i will try this.
ProgramFOX 26-Feb-13 12:51pm
   
You're welcome!
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

You can try below code by using this C# Excel[^]library, but it is also a commercial api like Microsoft Excel,it works fine in my project,hope you goodluck:
namespace textboxtoexcel
{
    public partial class Form1 : Form
    {
        private bool stop = false;
        private Workbook workbook = null;
        private Worksheet worksheet = null;
        private int rowIndex = 0;
        private String fileName = null;
        public Form1()
        {
            InitializeComponent();
        }
        private void labelSize_TextChanged(object sender, EventArgs e)
        {
            if (stop)
            {
                return;
            }
            String no = String.Format("No. {0}", rowIndex);
            rowIndex++;
            worksheet[rowIndex, 1].Text = no;
            worksheet[rowIndex, 2].Text = this.labelSize.Text;
        }
        private void InitWorkbook()
        {
            workbook = new Workbook();
            workbook.CreateEmptySheets(1);
            worksheet = workbook.Worksheets[0];
            worksheet.Name = "image size";
            worksheet.Range[1, 1].Text = "No";
            worksheet.Range[1, 2].Text = "Size Data";
            rowIndex = 1;
            fileName = String.Format("image-size-{0}.xls", Guid.NewGuid());
        }
        private void btnDemoStart_Click(object sender, EventArgs e)
        {
            this.btnOpenExcel.Enabled = false;
            this.stop = false;
            this.InitWorkbook();
            Random random = new Random();
            new Thread(() =>
            {
                while(!this.stop)
                {
                    int width = random.Next(1024);
                    int height = random.Next(1024);
                    this.Invoke(new Action(() =>
                    {
                        this.labelSize.Text = String.Format("{0}, {1}", width, height);
                    }));
                    Thread.Sleep(1000);
                }
            }).Start();
        }
        private void btnDemoStop_Click(object sender, EventArgs e)
        {
            this.stop = true;
            this.btnOpenExcel.Enabled = true;
            this.workbook.SaveToFile(fileName);
        }
        private void btnOpenExcel_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(fileName);
        }
    }
}
  Permalink  
v2
Comments
muthuu 25-Feb-13 21:49pm
   
Thank you for your help.i will try this.
Lacy00 26-Feb-13 20:54pm
   
Hope it cna help you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160919.1 | Last Updated 25 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100