要编辑导入的Excel文件的DataGridView的值,您可以按照以下步骤进行操作:
using Excel = Microsoft.Office.Interop.Excel;
DataGridView dataGridView1 = new DataGridView();
private void button1_Click(object sender, EventArgs e)
{
// 创建一个OpenFileDialog实例
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// 设置对话框的标题
openFileDialog1.Title = "选择Excel文件";
// 设置对话框的筛选器
openFileDialog1.Filter = "Excel文件|*.xlsx;*.xls";
// 显示对话框
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// 获取选择的文件路径
string filePath = openFileDialog1.FileName;
// 创建Excel应用程序对象
Excel.Application excelApp = new Excel.Application();
// 打开Excel文件
Excel.Workbook workbook = excelApp.Workbooks.Open(filePath);
// 获取第一个工作表
Excel.Worksheet worksheet = workbook.Sheets[1];
// 获取工作表中的数据范围
Excel.Range range = worksheet.UsedRange;
// 将Excel数据导入到DataGridView控件中
object[,] data = range.Value;
int rowCount = data.GetLength(0);
int columnCount = data.GetLength(1);
for (int i = 1; i <= rowCount; i++)
{
dataGridView1.Rows.Add();
for (int j = 1; j <= columnCount; j++)
{
dataGridView1.Rows[i - 1].Cells[j - 1].Value = data[i, j];
}
}
// 关闭Excel应用程序
excelApp.Quit();
}
}
下一篇:编辑导入模块的字典失败