[英]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.我设法使用 IExcelDataReader 从 Excel 文件中读取,现在我希望写入现有 Excel 文件中的特定单元格,因此我需要指定应插入数据的文件、列和行的路径。 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.但获取的类型或命名空间名称“应用程序”在命名空间 Excel 中不存在。 And the same for "Workbook".
“工作簿”也是如此。
I added the references Microsoft.Office.Interop.Excel and Office.我添加了参考 Microsoft.Office.Interop.Excel 和 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):要写入单元格,您可以使用以下内容(假设您已经有一个
Worksheet
对象):
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.您也可以尝试使用一些 rpa 工具(例如 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.