gpt4 book ai didi

c# - 如何使用 openFileDialog 打开 excel 文件

转载 作者:行者123 更新时间:2023-11-30 13:58:28 24 4
gpt4 key购买 nike

我很难弄明白这一点。我想在按钮单击事件上执行操作以打开一个 filedialog 窗口,用户可以在该窗口中选择一个 excel 文件,然后该文件将在 excel 中打开。

我已经创建了 filebox 并且我能够让 excel 打开一个新文件,但我不知道如何让这两者相结合。

我尝试使用的是如下,

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

private void button1_Click(object sender, EventArgs e)
{
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
MessageBox.Show(sr.ReadToEnd());
sr.Close();
}
}
}

我打算用它来打开excel

Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.Workbooks.Open(filename);

最佳答案

您应该将 excel 和 wb 声明为表单的字段。有点像

partial class MyForm : Form
{
private Excel.Application _excel;
private Excel.Workbook _wb;
// and so on
}

那你应该替换

System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
MessageBox.Show(sr.ReadToEnd());
sr.Close();

_excel = new Excel.Application();
_wb = _excel.Workbooks.Open(openFileDialog1.FileName);

关于c# - 如何使用 openFileDialog 打开 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16784040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com