如何在 C# 中打开 Excel 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/464902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open an Excel file in C#?
提问by tksy
I am trying to convert some VBAcode to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work?
我正在尝试将一些VBA代码转换为 C#。我是 C# 的新手。目前我正在尝试从文件夹中打开一个 Excel 文件,如果它不存在,则创建它。我正在尝试类似以下内容。我怎样才能让它工作?
Excel.Application objexcel;
Excel.Workbook wbexcel;
bool wbexists;
Excel.Worksheet objsht;
Excel.Range objrange;
objexcel = new Excel.Application();
if (Directory("C:\csharp\error report1.xls") = "")
{
wbexcel.NewSheet();
}
else
{
wbexcel.Open("C:\csharp\error report1.xls");
objsht = ("sheet1");
}
objsht.Activate();
采纳答案by abatishchev
You need to have installed Microsoft Visual Studio Tools for Office (VSTO).
您需要安装 Microsoft Visual Studio Tools for Office (VSTO)。
VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.
可以在 Visual Studio 安装程序中的工作负载 > Web 和云 > Office/SharePoint 开发下选择 VSTO。
After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel
via 'Add Reference... > Assemblies' dialog.
之后创建通用 .NET 项目并 Microsoft.Office.Interop.Excel
通过“添加引用...> 程序集”对话框添加引用。
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value
is a special reflection struct for unnecessary parameters replacement
Missing.Value
是一个特殊的反射结构,用于不必要的参数替换
In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library
. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library
, or an older version, but it is the same process to include.
在较新的版本中,所需的程序集引用称为Microsoft Excel 16.0 Object Library
. 如果您没有安装最新版本,您可能安装了Microsoft Excel 15.0 Object Library
或旧版本,但包含的过程相同。
回答by Frederick The Fool
For opening a file, try this:
要打开文件,请尝试以下操作:
objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
你必须提供那些看起来很愚蠢的“缺失”参数。如果您在 VB.Net 中编写相同的代码,您就不需要它们,但您无法在 C# 中避免它们。
回答by Mats Fredriksson
It's easier to help you if you say what's wrong as well, or what fails when you run it.
如果您还说出了什么问题,或者运行时出现了什么问题,那么帮助您会更容易。
But from a quick glance you've confused a few things.
但是,快速浏览一下,您已经混淆了一些事情。
The following doesn't work because of a couple of issues.
由于几个问题,以下不起作用。
if (Directory("C:\csharp\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
您要做的是创建一个新的 Directory 对象,该对象应该指向一个文件,然后检查是否有任何错误。
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
您实际上正在尝试调用名为 Directory() 的函数,然后为结果分配一个字符串。这是行不通的,因为 1/ 您没有名为 Directory(string str) 的函数,并且您无法分配给函数的结果(您只能为变量分配一个值)。
What you should do (for this line at least) is the following
你应该做的(至少对于这一行)如下
FileInfo fi = new FileInfo("C:\csharp\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
至于为什么 Excel 代码不起作用,您必须检查 google 应该能够为您提供的 Excel 库的文档。
回答by Tamas Czinege
Is this a commercial application or some hobbyist / open source software?
这是商业应用程序还是一些业余爱好者/开源软件?
I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.
我之所以这么问是因为根据我的经验,由于不同的原因,所有免费的 .NET Excel 处理替代方案都有严重的问题。对于业余爱好者,我通常最终将 jExcelApi 从 Java 移植到 C# 并使用它。
But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.
但是如果这是一个商业应用程序,你最好购买第三方库,比如Aspose.Cells。相信我,它完全值得,因为它节省了大量时间,而且时间不是免费的。
回答by Jairaj
Microsoft.Office.Interop.Excel.Application excapp;
excapp = new Microsoft.Office.Interop.Excel.Application();
object misval=System.Reflection.Missing.Value;
Workbook wrkbuk = new Workbook();
Worksheet wrksht = new Worksheet();
wrkbuk = excapp.Workbooks._Open(@"C:\Users\...\..._template_v1.0.xlsx", misval, misval,
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);
wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);
回答by Mennan
FileInfo fi = new FileInfo("C:\test\report.xlsx");
if(fi.Exists)
{
System.Diagnostics.Process.Start(@"C:\test\report.xlsx");
}
else
{
//file doesn't exist
}
回答by bvgheluwe
回答by rudenaggar
you should open like this
你应该这样打开
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
source : http://csharp.net-informations.com/excel/csharp-open-excel.htm
来源:http: //csharp.net-informations.com/excel/csharp-open-excel.htm
ruden
鲁登
回答by Flane
private void btnChoose2_Click(object sender, EventArgs e)
{
OpenFileDialog openfileDialog1 = new OpenFileDialog();
if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.btnChoose2.Text = openfileDialog1.FileName;
String filename = DialogResult.ToString();
var excelApp = new Excel.Application();
excelApp.Visible = true;
excelApp.Workbooks.Open(btnChoose2.Text);
}
}
回答by Gaurav Bari
Code :
代码 :
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled=false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excell File |*.xlsx;*,xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
string extn = Path.GetExtension(ofd.FileName);
if (extn.Equals(".xls") || extn.Equals(".xlsx"))
{
filename = ofd.FileName;
if (filename != "")
{
try
{
string excelfilename = Path.GetFileName(filename);
}
catch (Exception ew)
{
MessageBox.Show("Errror:" + ew.ToString());
}
}
}
}