C#如何从WinForm打开excel文件(如果存在),如果不存在则创建excel文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10615339/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:30:57  来源:igfitidea点击:

C# how to Open excel file if it exists, create excel file if it doesn't, from WinForm?

c#excel

提问by user1396678

I'm making a program that works with Excel files. I need it to try to open an existing Excel file, or create a new one if it doesn't exist, for read and write options. And I have to do this without using OleDb. So the thing is, when I click the button it tries to create a new Excel file, even if I already have that file in the directory. Any ideas on how to fix this? All the user input must be done from WinForm. Here's my code:

我正在制作一个适用于 Excel 文件的程序。我需要它来尝试打开一个现有的 Excel 文件,或者如果它不存在,则创建一个新文件,用于读取和写入选项。我必须在不使用 OleDb 的情况下执行此操作。所以问题是,当我单击按钮时,它会尝试创建一个新的 Excel 文件,即使我已经在目录中拥有该文件。有想法该怎么解决这个吗?所有用户输入都必须从 WinForm 完成。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace test2
{
    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application oXL;
        Microsoft.Office.Interop.Excel._Workbook oWB;
        Microsoft.Office.Interop.Excel._Worksheet oSheet;
        Microsoft.Office.Interop.Excel.Range oRng;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        FileInfo fi = new FileInfo(@"C:\Users\User\Desktop\data.xls");
        if (!fi.Exists)
        {
            oXL = new Microsoft.Office.Interop.Excel.Application();
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
            oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

            oSheet.Cells[1, 1] = "First Name";
            oSheet.Cells[1, 2] = "Last Name";
            oSheet.Cells[1, 3] = "Full Name";
            oSheet.Cells[1, 4] = "Age";

            oSheet.get_Range("A1", "D1").Font.Bold = true;
            oSheet.get_Range("A1", "D1").VerticalAlignment =
            Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;      
        }
        else
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            string myPath = (@"C:\Users\User\Desktop\data.xlsx");
            excelApp.Workbooks.Open(myPath);
            excelApp.Visible = true;                
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

}

}

Also, I would be grateful if someone could give me a code example for saving and closing Excel files without interaction with the user. The user would input data then click button and it would automatically save and close the Excel document, without any pop-ups being displayed to the user.

另外,如果有人能给我一个代码示例,在不与用户交互的情况下保存和关闭 Excel 文件,我将不胜感激。用户输入数据然后单击按钮,它会自动保存并关闭 Excel 文档,不会向用户显示任何弹出窗口。

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            string myPath = (@"C:\Users\User\Desktop\data.xlsx");
            excelApp.Workbooks.Open(myPath);
            excelApp.Visible = false;
            int rowIndex = 2; int colIndex = 2;
            excelApp.Cells[rowIndex, colIndex] = textBox1.Text;
            //how do I save workbook?
            //how do I colose Workbook?

Thanks in advance.

提前致谢。

回答by Dimitris

First of all I would definitely recommend using Visual Studio Tools for Office (VSTO) if you happen to have a newish version of Visual Studio such as 2010. You can create Excel projects within that framework and speed up your development time. If you want to find out more about it look here: http://msdn.microsoft.com/en-US/office/hh133430.aspx

首先,如果您碰巧拥有 Visual Studio 的新版本(例如 2010),我肯定会建议您使用 Visual Studio Tools for Office ( VSTO)。您可以在该框架内创建 Excel 项目并加快您的开发时间。如果您想了解更多信息,请看这里:http: //msdn.microsoft.com/en-US/office/hh133430.aspx

To answer your question on saving your Excel workbook from a WinForm application you can do the following:

要回答有关从 WinForm 应用程序保存 Excel 工作簿的问题,您可以执行以下操作:

excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;

excelApp.ActiveWorkbook.Save();

excelApp.ScreenUpdating = true;
excelApp.DisplayAlerts = true;

Hope that helps but let us know if there is anything else there.

希望有帮助,但如果还有其他问题,请告诉我们。

回答by user2369270

excelWorkbook.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close();
excelApp.Quit();