要在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程序。