简体   繁体   中英

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. 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) ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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