简体   繁体   English

如何使用C#获取Excel工作表中给定行的列数?

[英]How to get the number of columns in the given row in Excel sheet with C#?

I am using C# Interop Excel and I have a Excel sheet with the column names in the first row and some data below it. 我正在使用C#Interop Excel,并且有一个Excel工作表,其第一行的列名称及其下的一些数据。 So I want to get the number of the column names which means the number of columns in the first row. 所以我想获取列名的数量,这意味着第一行中的列数。

I have tried something like that but it returns incorrect value: 我已经尝试过类似的方法,但是返回的值不正确:

int colCount = ((Excel.Range)xlWorkSheet.Rows[1]).EntireRow.Columns.Count;

Any idea how can I get the first row as a range and then get count of the columns in this range? 知道如何将第一行作为一个范围,然后获取该范围内的列数吗?

Try this ... 尝试这个 ...

var xlApplication = new Microsoft.Office.Interop.Excel.Application();
var xlWorkbook = xlApplication.Workbooks.Open("YourWorkbook.xlsx");
var xlWorksheets = xlWorkbook.Worksheets;
var xlWorksheet = xlWorksheets[1] as Worksheet;

var columnCount = xlWorksheet.Columns.Count;

... or based on what you're asking, for the last column in a row based on usage (the example is for row 1, loop if you need to or specify a particular row of your choice) ... ...或根据您的要求,根据使用情况针对行中的最后一列(示例针对第1行,如果需要或指定您选择的特定行,则进行循环)...

var columnCount = xlWorksheet.Cells[1, xlWorksheet.Columns.Count].End[XlDirection.xlToLeft].Column;

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

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