打开并展示一个excel文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ShowExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLoadExcel_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
LoadExcelData(filePath);
}
}
private void LoadExcelData(string filePath)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(filePath);
Excel.Worksheet worksheet = workbook.Sheets[1]; // Assuming you want to read data from the first sheet
int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;
// Create a DataTable to hold the Excel data
DataTable excelDataTable = new DataTable();
// Add columns to DataTable
for (int col = 1; col <= colCount; col++)
{
excelDataTable.Columns.Add("Column" + col.ToString());
}
// Add data to DataTable
for (int row = 1; row <= rowCount; row++)
{
DataRow dataRow = excelDataTable.NewRow();
for (int col = 1; col <= colCount; col++)
{
dataRow["Column" + col.ToString()] = worksheet.Cells[row, col].Value;
}
excelDataTable.Rows.Add(dataRow);
}
// Bind DataTable to DataGridView
dataGridView1.DataSource = excelDataTable;
// Release Excel objects
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
}