繁体   English   中英

如何在新的excel工作簿中创建空白工作表

[英]How to create a blank worksheet into the new excel workbook

catch (COMException ex)
{
    /*************Create new excel program in no running excel program*************/
    //xlApp = new Excel.Application();
    //xlApp.DisplayAlerts = false;
    //xlApp.Visible = true;
    //xlApp.ScreenUpdating = true;
    //xlApp.WindowState = Excel.XlWindowState.xlMaximized;

    //OpenExcelCB.Checked = true;
    /*************Create new excel program in no running excel program*************/

    HandleRunningException("Error occurs ...", ex);

    MessageBox.Show("Please open Excel!");
    //this.close();
}

我想对上面的代码进行调整。 但是,当我删除注释标签并尝试运行该程序时。 它只打开 excel 应用程序,而没有新的工作表。

谁能帮我看看我的程序是否有问题或者是否有任何遗漏?

看看以下是否满足您的需求(有这个问题)。

  • 如果文件存在,将其删除以确保代码有效
  • 重命名第一个工作表
  • 添加新工作表
  • 保存新文件
  • 验证所有对象都已释放
  • (可选)打开新文件

excel操作类

using System;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelInteropApp.Classes
{
    public class ExcelOperations
    {
        public delegate void OnAction(string sender);
        public static event OnAction ActionHandler;
        /// <summary>
        /// create an excel file, rename sheet1 (default sheet),
        /// create another worksheet, rename it and re-order to end.
        /// </summary>
        /// <param name="fileName">path and file name for excel file</param>
        /// <param name="firstWorkSheetName">name for default sheet</param>
        /// <param name="secondWorkSheetName">name for newly added sheet</param>
        public static (bool success, Exception exception) CreateExcelFile(string fileName, string firstWorkSheetName, string secondWorkSheetName, bool open)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                Excel.Application xlApp;
                Excel.Workbooks xlWorkBooks;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                Excel.Sheets xlWorkSheets;

                xlApp = new Excel.Application { DisplayAlerts = false };

                xlWorkBooks = xlApp.Workbooks;
                xlWorkBook = xlWorkBooks.Add();

                xlWorkSheets = xlWorkBook.Sheets;


                xlWorkSheet = (Excel.Worksheet)xlWorkSheets[1];
                xlWorkSheet.Name = firstWorkSheetName;

                ActionHandler?.Invoke("renamed first sheet");
                
                Excel.Worksheet xlNewSheet = (Excel.Worksheet)xlWorkSheets
                    .Add(xlWorkSheets[1], 
                        Type.Missing, 
                        Type.Missing, 
                        Type.Missing);

                xlNewSheet.Move(System.Reflection.Missing.Value, xlWorkSheets[xlWorkSheets.Count]);

                xlNewSheet.Name = secondWorkSheetName;

                ActionHandler?.Invoke("Done with add sheet");

                Marshal.FinalReleaseComObject(xlNewSheet);
                xlNewSheet = null;
                xlWorkBook.SaveAs(fileName);

                ActionHandler?.Invoke("Saved file");

                xlWorkBook.Close();
                xlApp.UserControl = true;
                xlApp.Quit();

                Marshal.FinalReleaseComObject(xlWorkSheets);
                xlWorkSheets = null;

                Marshal.FinalReleaseComObject(xlWorkSheet);
                xlWorkSheet = null;

                Marshal.FinalReleaseComObject(xlWorkBook);
                xlWorkBook = null;

                Marshal.FinalReleaseComObject(xlWorkBooks);
                xlWorkBooks = null;

                Marshal.FinalReleaseComObject(xlApp);
                xlApp = null;

                ActionHandler?.Invoke($"Clean-up: {(Process.GetProcesses().Any((p) => p.ProcessName.Contains("EXCEL")) ? "Released" : "Not released")}");

                if (open)
                {
                    Process.Start(fileName);
                }
                
                return (true, null);
            }
            catch (Exception exception)
            {
                return (false, exception);
            }
        }


    }
}

在 windows 窗体中的使用

private void CreateExcelButton1_Click(object sender, EventArgs e)
{
    ExcelOperations.ActionHandler += ExcelOperationsOnActionHandler;
    string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demo.xlsx");
    string firstSheet = "Karen";
    string secondSheet = "Karen 1";
    
    var (success, exception) = ExcelOperations.CreateExcelFile(fileName,firstSheet, secondSheet, true);
    if (success == false)
    {
        Console.WriteLine(exception.Message);
    }

    ExcelOperations.ActionHandler -= ExcelOperationsOnActionHandler;

}

private void ExcelOperationsOnActionHandler(string sender)
{
    Console.WriteLine(sender);
}

暂无
暂无

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

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