WeldingExcel.cs
2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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;
}
}
}