简体   繁体   English

哪种方法使用C#从Excel读取单元格?

[英]Which way to read a cell from Excel using C#?

I have found two ways those were being used by people if we want to read or write to a cell in an excel. 如果我们想在Excel中读取或写入单元格,我发现了人们正在使用的两种方式。

Declaration: 宣言:

Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook srcWorkBook = ExcelApp.Workbooks.Open(@"C:\test.xls");
Excel.Worksheet srcWorkSheet = srcWorkBook.Worksheets[1];
Excel.Range srcRange = srcWorkSheet.UsedRange;

Usage 1: 用法1:

srcWorkSheet.Cells[1, 1].value2 = "foo bar";

Usage 2: 用法2:

srcRange.Cells[2, 2].Value2 = "foo bar";

Which one is the best way to use ? 哪一种是最佳使用方式? or it's all fine in .NET ? 还是在.NET中一切正常?

The two ways are very different. 两种方式非常不同。

srcWorkSheet.Cells[1, 1].value2 = "foo bar";

srcRange.Cells[2, 2].Value2 = "foo bar";
  • The 2. usage takes the cell on the 2. row, 2. column of the UsedRange . 2.用法将单元格放在UsedRange的2.行2.列上。 If the UsedRange in Excel is B2:D5 , it would put value at C3 : 如果Excel中的UsedRangeB2:D5 ,它将把值放在C3

在此处输入图片说明


  • Having a variable named Range as the Range class is really not a great idea. 将名为Range的变量作为Range类确实不是一个好主意。 The same goes for WorkSheet and WorkBook . WorkSheetWorkBook

Either option will work, but they get messy as soon as you have to modify the layout of the worksheet. 这两种方法都可以使用,但是一旦您必须修改工作表的布局,它们就会变得混乱。

If it's an option, I like to add named ranges. 如果可以选择,我想添加命名范围。 This works particularly well if you're using a template where you can modify the "starting" state of the workbook. 如果您使用的模板可以在其中修改工作簿的“开始”状态,则此方法特别有用。

Let's say you have a series of columns, and one of them contains the "foo" value. 假设您有一系列列,其中一个包含“ foo”值。 You can add a name like "fooColumn" to the entire column or the top cell in the column. 您可以在整个列或该列的顶部单元格中添加一个名称,例如“ fooColumn”。

Then you can get the column number using 然后您可以使用获取列号

worksheet.Range("fooColumn").Column

That protects you from having to manually edit column or row numbers all over the place if you move elements around on your worksheet. 如果您在工作表上四处移动元素,则不必在各处手动编辑列号或行号。


And to second what others have said, use EPPlus instead of Interop. 其次,请使用EPPlus而不是Interop。 You can still use named ranges. 您仍然可以使用命名范围。 But EPPlus is good and Interop can bring all sorts of pain when COM objects aren't released. 但是EPPlus很好,当不释放COM对象时,Interop会带来各种各样的痛苦。 Interop automates an application that manipulates the file. Interop使处理文件的应用程序自动化。 EPPlus just works with the file. EPPlus仅适用于该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM