开发者

How to write to specific cells in an existing Excel (xlsc) file with C#

I managed to read from an Excel file using IExcelDataReader, now I wish to write to specific cells in an existing Excel file, so I need to specify path to the file, column and row where the data should be inserted. I googled and found some examples but there were disputes whether the solutions worked or not. So which is the simplest way of doing this (code examples appriciated). Thanks.

Edit: So I tried doing this:

Excel.Application ExcelObj = new Excel.Application();
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open("Path", 0, true, 5,开发者_开发知识库"", "", true,     Excel.xlWindows, "\t", false, false,0, true); 

But get the type or namespace name "Application" does not exist in the namespace Excel. And the same for "Workbook".

I added the references Microsoft.Office.Interop.Excel and Office. What more do I need?


Using the following should sort out your namespace issues:

using Excel = Microsoft.Office.Interop.Excel;

To write to a cell you can use the following (assuming you already have a Worksheet object):

xlWorksheet.Cells["1", "A"] = "Foo";

This is the method I've been using for a couple of years and it's worked without fail every time.


You can also try doing this using some rpa tool such as G1ANT. It will make your work much easy. Try this simple code for updating cell:

addon xlsx version 4.101.0.0
addon core version 4.101.0.0
addon language version 4.103.0.0
xlsx.open C:\Documents\TestBook.xlsx createifnotexist true
xlsx.setvalue value 123 row 1 colname a
xlsx.close
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜