Writing data to Excel cells, C #

Reading from Excel works fine. But I have problems writing new data to worksheet3 and cells [8.2]. How to fix this code?

I get an error message:

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

But I can read from this file using another 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); 
+4
source share
5 answers

The way to set the cell contents is as follows:

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

I am using Excel 2010.

+3
source

You cannot set a range for a string:

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

Try something like:

 xlRange = (Excel.Range) xlWorkSheet.Cells[8, 2]; xlRange.Value = "Salary"; 
0
source

Your code looks fine. The problem may be in the file.

Open the file in Excel. Do you see a write protection message? Make sure you can manually modify its contents and save the file. Give it a try.

enter image description here

0
source

You open the excel file in readonly mode.

 xlApp.Workbooks.Open("C:\\Base.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); 

And you set editable to false. This is probably the reason you cannot edit the file ...

 xlApp.Workbooks.Open("C:\\Base.xls", 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0); 
0
source

Take a look at this line in the code:

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

The third parameter determines that your shoul file will be read-only. You set it to true that meens you cannot modify your file. I think that’s why you have a file inaccessible error.

0
source

Source: https://habr.com/ru/post/1346451/


All Articles