要在Winform中导入Excel数据,可以使用Microsoft.Office.Interop.Excel库。以下是一个示例代码,演示如何导入Excel数据到Winform中的DataGridView控件:
using Microsoft.Office.Interop.Excel;
using System;
using System.Data;
using System.Windows.Forms;
namespace ExcelImportDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook excelWorkbook = excelApp.Workbooks.Open(fileName);
Worksheet excelWorksheet = excelWorkbook.Sheets[1];
Range excelRange = excelWorksheet.UsedRange;
DataTable dt = new DataTable();
for (int i = 1; i <= excelRange.Columns.Count; i++)
{
dt.Columns.Add(excelRange.Cells[1, i].Value2.ToString());
}
for (int i = 2; i <= excelRange.Rows.Count; i++)
{
DataRow row = dt.NewRow();
for (int j = 1; j <= excelRange.Columns.Count; j++)
{
row[j - 1] = excelRange.Cells[i, j].Value2;
}
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
excelWorkbook.Close();
excelApp.Quit();
}
}
}
}
在上面的代码中,首先创建一个OpenFileDialog来让用户选择Excel文件,然后使用Microsoft.Office.Interop.Excel库来打开Excel文件并读取数据。读取的数据将被存储在一个DataTable中,最后将DataTable绑定到Winform中的DataGridView控件上显示出来。
请注意,使用Microsoft.Office.Interop.Excel库需要安装Excel程序并引用对应的COM组件。也可以考虑使用第三方库如EPPlus来处理Excel文件,避免依赖于安装Excel程序。