C#中点击按钮BUTTON1,选择电脑中的一张EXCEL表,选中后将EXCEL表中名为“订单总表”的表格所有数据导入dataGridView1的C#代码
时间: 2024-11-09 10:24:54 浏览: 8
在C#中,你可以使用`OpenFileDialog`来让用户选择Excel文件,然后利用`Microsoft.Office.Interop.Excel`库来操作Excel表格。以下是一个简单的示例代码片段,展示如何实现这个功能:
```csharp
using System;
using System.Data;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
public partial class Form1 : Form
{
private OleDbConnection excelConnection;
public Form1()
{
InitializeComponent();
}
private void BUTTON1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files (*.xlsx;*.xls)|*.xlsx;*.xls";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
try
{
// 创建Excel应用对象
Application excelApp = new Application();
// 打开Excel工作簿
Workbook workbook = excelApp.Workbooks.Open(filePath);
// 获取第一个工作表
Worksheet worksheet = workbook.Sheets[1]; // 如果"订单总表"在第一张,这里不需要索引
// 提取数据到DataTable
DataTable dataTable = new DataTable();
using (OleDbConnection odbcConnection = new OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0 Xml;HDR=YES;'"))
{
odbcConnection.Open();
OleDbCommand command = new OleDbCommand("SELECT * FROM [订单总表$]", odbcConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(dataTable);
}
// 关闭Excel工作簿
workbook.Close(false); // 强制关闭,忽略警告
// 将DataTable的数据填充到DataGridView
dataGridView1.DataSource = dataTable;
excelApp.Quit(); // 释放资源
}
catch (Exception ex)
{
MessageBox.Show($"错误:{ex.Message}");
}
}
}
}
```
阅读全文