C# Excel 导入 得到DataTable xls xlsx

添加引用,没有的去NuGet下载

using Excel = Microsoft.Office.Interop.Excel;  

方法

public DataTable ImportExcelToDataTable(string filePath)  
{  
    DataTable dataTable = new DataTable();  
  
    try  
    {  
        Excel.Application excelApp = new Excel.Application();  
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath);  
        Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];  
        Excel.Range excelRange = excelWorksheet.UsedRange;  
  
        int rowCount = excelRange.Rows.Count;  
        int colCount = excelRange.Columns.Count;  
  
        // Adding the Columns to the DataTable  
        for (int i = 1; i <= colCount; i++)  
        {  
            string columnName = excelRange.Cells[1, i].Value2.ToString();  
            dataTable.Columns.Add(columnName);  
        }  
  
        // Adding the Rows to the DataTable  
        for (int i = 2; i <= rowCount; i++)  
        {  
            DataRow dataRow = dataTable.NewRow();  
            for (int j = 1; j <= colCount; j++)  
            {  
                if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)  
                    dataRow[j - 1] = excelRange.Cells[i, j].Value2.ToString();  
            }  
            dataTable.Rows.Add(dataRow);  
        }  
  
        // Release the resources  
        GC.Collect();  
        GC.WaitForPendingFinalizers();  
  
        // Close and release  
        Marshal.ReleaseComObject(excelWorksheet);  
        excelWorkbook.Close();  
        Marshal.ReleaseComObject(excelWorkbook);  
  
        // Quit and release  
        excelApp.Quit();  
        Marshal.ReleaseComObject(excelApp);  
    }  
    catch (Exception ex)  
    {  
        Console.WriteLine("Error: Could not read the Excel file. " + ex.Message);  
    }  
  
    return dataTable;  
}  

调用

        private void button2_Click(object sender, EventArgs e)
        {
            var table= new DataTable();
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
                openFileDialog.Title = "Select an Excel File";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    table=ImportExcelToDataTable(openFileDialog.FileName);
                    dataGridView1.DataSource = table;
                }
            }
        }

你可能感兴趣的:(c#,excel,开发语言)