Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to cells in Excel, C#

Tags:

c#

excel

interop

reading from Excel cells works perfect. But i have problems with writing new data to worksheet3 and cells[8,2].. How to fix this code?

I'm getting error:

System.Runtime.InteropServices.COMException: File not available.

But i can read from this file using other button.

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("C:\\Base.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);

// range = xlWorkSheet.UsedRange;

//  Object[,] saRet;
//  saRet = (System.Object[,])range.get_Value(Missing.Value);

xlWorkSheet.Cells[8, 2] = "Salary";

xlWorkBook.Close(true, null, null);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
like image 446
Elfoc Avatar asked Apr 03 '11 15:04

Elfoc


2 Answers

The way I set the content of the cell is like this:

 xlWorkSheet.Cells[8, 2].Value = "Salary";

I am using Excel 2010.

like image 132
gyurisc Avatar answered Oct 05 '22 04:10

gyurisc


You can't set a range to a string:

xlWorkSheet.Cells[8, 2] = "Salary"; 

Try something like:

xlRange = (Excel.Range) xlWorkSheet.Cells[8, 2];
xlRange.Value = "Salary";
like image 22
Joe Avatar answered Oct 05 '22 03:10

Joe