WeldingExcel.cs 2.15 KB
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace HHWelding.WeldingTask
{
    public class WeldingExcel
    {
        public void ImportExcelToDataGrid(string filename)
        {
            // 创建一个Excel应用程序对象
            Application excelApp = new Application();
            // 打开Excel文件,将路径替换为实际的Excel文件路径
            Workbook workbook = excelApp.Workbooks.Open(filename);
            // 获取第一个工作表
            Worksheet worksheet = (Worksheet)workbook.Sheets[1];
            // 获取已使用区域的行数和列数
            int rowCount = worksheet.UsedRange.Rows.Count;
            int colCount = worksheet.UsedRange.Columns.Count;

            // 创建一个DataTable来存储Excel数据
            System.Data.DataTable dataTable = new System.Data.DataTable();

            // 添加列到DataTable
            for (int col = 1; col <= colCount; col++)
            {
                string columnName = worksheet.Cells[1, col].ToString();
                dataTable.Columns.Add(columnName);
            }

            // 添加行数据到DataTable
            for (int row = 2; row <= rowCount; row++)
            {
                DataRow dataRow = dataTable.NewRow();
                for (int col = 1; col <= colCount; col++)
                {
                    object cellValue = worksheet.Cells[row, col];
                    dataRow[col - 1] = cellValue;
                }
                dataTable.Rows.Add(dataRow);
            }

            // 关闭Excel文件和应用程序
            workbook.Close(false);
            excelApp.Quit();
            // 释放COM对象
            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excelApp);

            //return dataTable.DefaultView;
            // 将DataTable作为数据源绑定到DataGrid
            //dataGrid.ItemsSource = dataTable.DefaultView;
        }
    }
}