C# 将 Excel 数据按列写入 DataTable 代码示例
using System;using System.Data;using Excel = Microsoft.Office.Interop.Excel;namespace ExcelToDataTable{class Program{static void Main(string[] args){Excel.Application excelApp = new Excel.Application();Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\Path\To\Your\Excel\File.xlsx");Excel.Worksheet excelWorksheet = excelWorkbook.Sheets[1];Excel.Range excelRange = excelWorksheet.UsedRange;DataTable dataTable = new DataTable();for (int columnIndex = 1; columnIndex <= 10; columnIndex++){string columnName = "Column " + columnIndex;dataTable.Columns.Add(columnName, typeof(string));}int rowCount = excelRange.Rows.Count;int columnCount = excelRange.Columns.Count;for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++){DataRow dataRow = dataTable.NewRow();for (int columnIndex = 1; columnIndex <= columnCount && columnIndex <= 10; columnIndex++){dataRow[columnIndex - 1] = excelRange.Cells[rowIndex, columnIndex].Value.ToString();}dataTable.Rows.Add(dataRow);}excelWorkbook.Close();excelApp.Quit();foreach (DataRow row in dataTable.Rows){foreach (var item in row.ItemArray){Console.Write(item + "\t");}Console.WriteLine();}Console.ReadLine();}}}
原文地址: https://www.cveoy.top/t/topic/pYuU 著作权归作者所有。请勿转载和采集!