简体   繁体   English

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

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

I'm making a program that works with Excel files. 我正在制作一个适用于Excel文件的程序。 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. 我需要它来尝试打开一个现有的Excel文件,或者创建一个新的Excel文件(如果不存在),以供读取和写入。 And I have to do this without using OleDb. 而且我必须不使用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. 就是这样,当我单击按钮时,即使目录中已经有该文件,它也会尝试创建一个新的Excel文件。 Any ideas on how to fix this? 有想法该怎么解决这个吗? All the user input must be done from WinForm. 所有用户输入都必须从WinForm完成。 Here's my code: 这是我的代码:

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. 另外,如果有人可以给我一个代码示例,用于保存和关闭Excel文件而不与用户交互,我也将不胜感激。 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文档,而不会向用户显示任何弹出窗口。

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. 提前致谢。

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. 首先,如果您碰巧拥有Visual Studio的最新版本(例如2010),我肯定会建议使用Visual Studio Tools for Office( VSTO )。您可以在该框架内创建Excel项目并加快开发时间。 If you want to find out more about it look here: http://msdn.microsoft.com/en-US/office/hh133430.aspx 如果您想找到更多关于它的信息,请看这里: 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. 希望有帮助,但请告诉我们是否还有其他内容。

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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM