C# 使用 Excel Interop 获取 Excel 文件列名
使用C#的Excel Interop库获取Excel文件中的列名,可以通过Range.Cells属性获取指定范围的单元格对象,然后使用单元格对象的Value属性获取单元格的值。以下是一个示例代码,演示如何使用ColumnIndex获取Excel文件中的列名:\n\ncsharp\nusing Excel = Microsoft.Office.Interop.Excel;\n\npublic static void GetColumnNames(string filePath)\n{\n Excel.Application excelApp = new Excel.Application();\n Excel.Workbook workbook = excelApp.Workbooks.Open(filePath);\n Excel.Worksheet worksheet = workbook.Sheets[1]; // 假设要处理的是第一个工作表\n\n int columnCount = worksheet.UsedRange.Columns.Count;\n for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)\n {\n Excel.Range cell = worksheet.Cells[1, columnIndex];\n string columnName = cell.Value.ToString(); // 获取单元格的值并转换为字符串\n Console.WriteLine("Column {0}: {1}", columnIndex, columnName);\n }\n\n workbook.Close();\n excelApp.Quit();\n}\n\n\n在上述示例中,我们使用worksheet.UsedRange.Columns.Count获取工作表中的列数。然后,我们使用worksheet.Cells[1, columnIndex]获取第一行中指定列的单元格对象。最后,我们使用cell.Value.ToString()将单元格的值转换为字符串,即获取列名。\n\n请注意,这个示例使用了Excel Interop库,因此需要安装Microsoft Office套件并添加对Microsoft.Office.Interop.Excel的引用。
原文地址: https://www.cveoy.top/t/topic/p8W7 著作权归作者所有。请勿转载和采集!