Wie kann ich in C# ändern, ein Excel-Arbeitsblatt, speichern Sie es als einen anderen Namen und löschen Sie das original-Arbeitsblatt

Ich habe eine Windows Form-Anwendung bietet dem Benutzer ein open-Dialogfeld zu öffnen, einer Tabellenkalkulation.

Die Anwendung führt einige Aufgaben auf, die Tabelle Sortieren und löschen von leeren Zeilen. Dann wenn er fertig ist, führt es einen SaveAs mit dem aktuellen Datum als Teil des Dateinamens.

Nachdem das beendet ist, was ich will zu tun ist, löschen Sie die ursprüngliche Tabelle.

Ich bin mit Microsoft.Office.Interop.Excel.

Fand ich code hier auf StackOverflow ( Wie kann ich richtig aufzuräumen Excel-interop-Objekte? ), die zeigt, wie shutdown-Excel und der 3. Antwort in diesem Beitrag von nightcoder zeigten sogar eine Möglichkeit (die ich verwende) wird entfernt Excel die Registerkarte "Prozesse" des Task-Manager.

Dachte ich einmal, dass Excel geworfen wurde aus dem Task-Manager entfernen seiner eisigen tenticle-wie der Tod Griff mit der Datei versuche ich zu schließen, aber wie falsch ich bin.

Wenn der code zuvor auf die Datei.Löschen(MyFile) Befehl es sagt noch ich kann nicht diese Datei zu löschen, weil es ist ein eisiger tenticle-wie der Tod-Griff auf Sie oder so etwas.

Weiß jemand, wo ich finden kann, eine baseball-Fledermaus groß genug, um die app loslassen der Datei. Ich würde wirklich gerne, um es zu löschen.

==============================================================

7/22/2013 Update

Hier ist ein Teil von meinem code, die ich habe, so weit.

Was dieser code tut, ist dem Benutzer zu ermöglichen, wählen Sie eine excel-Tabelle, öffnen Sie Sie, benennen Sie es und schließen Sie es dann. Ich zog Sie heraus, einige der code, der manipuliert die Tabellenkalkulation, die ich nicht glaube, dass es notwendig war.

Was ich möchte für Sie zu tun ist, nachdem es gespeichert hat die Datei umbenannt ist, schließen Sie das original, öffnen Sie die umbenannte und die Anwendung zu beenden, während er das umbenannte Tabellenblatt geöffnet, die für weitere Bearbeitung.

Derzeit tut es das nicht. Es schafft nur die Tabelle mit dem neuen Namen und dann schließt die app und das Arbeitsblatt. Dann habe ich öffnen Sie die neue Tabelle manuell.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel; 

namespace Weekly_Stats_Organizer
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        string _ExcelFileName;

        private string ExcelFileName
        {
            get { return _ExcelFileName; }
            set { _ExcelFileName = value; }
        }
        private string DefaultPath = "C:\\My Documents\\Weekly Stats";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stream FileName = null;
            OpenFileDialog OpenExcelSpreadsheet = new OpenFileDialog();
            OpenExcelSpreadsheet.InitialDirectory = DefaultPath;
            OpenExcelSpreadsheet.Filter = "Excel 2003 (*.xls)|*.xls|Excel 2007 (*.xlsx)|*.xlsx";
            OpenExcelSpreadsheet.FilterIndex = 1;
            OpenExcelSpreadsheet.RestoreDirectory = true;
            if(OpenExcelSpreadsheet.ShowDialog() == DialogResult.OK)
            {
                if((FileName = OpenExcelSpreadsheet.OpenFile()) != null)
                {
                    ExcelFileName = ((System.Windows.Forms.FileDialog)(OpenExcelSpreadsheet)).FileName;
                    GenerateWorkbook();
                }
            }
        }

        private void GetExcel()
        {

            Excel.Application ExcelApp = null;
            Excel.Workbook ExcelWorkBook = null;
            Excel.Sheets ExcelSheets = null;
            Excel.Worksheet MySheet = null;
            try
            {

                DateTime CurrentDate = DateTime.Today;
                string FileName = DefaultPath + "\\" + CurrentDate.Year.ToString() + "-" + CurrentDate.Month.ToString("D2") + "-" + CurrentDate.Day.ToString("D2") + " Weekly Stats.xls";

                ExcelApp = new Excel.Application();
                ExcelApp.Visible = false;
                ExcelWorkBook = ExcelApp.Workbooks.Open(ExcelFileName, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

                ExcelSheets = ExcelWorkBook.Worksheets;

                MySheet = (Excel.Worksheet)ExcelSheets.get_Item("Sheet 1");

                ExcelWorkBook.SaveAs(FileName, Excel.XlFileFormat.xlWorkbookNormal, "", "", false, false,
                    Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, "", "", "");

                //GC.Collect();
                //GC.WaitForPendingFinalizers();

                Marshal.ReleaseComObject(MySheet);
                Marshal.ReleaseComObject(ExcelSheets);

                MySheet = null;
                ExcelSheets = null;

                ExcelWorkBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            }
            finally
            {
                Marshal.ReleaseComObject(ExcelWorkBook);

                int hWnd = ExcelApp.Application.Hwnd;
                TryKillProcessByMainWindowHwnd(hWnd);

                Marshal.ReleaseComObject(ExcelApp);
                ExcelWorkBook = null;
                ExcelApp = null;

                //if (File.Exists(ExcelFileName))
                //   File.Delete(ExcelFileName);

                System.Windows.Forms.Application.Exit();

            }


        }

        //=========================================================================================================================================
        //=========================================================================================================================================
        //=========================================================================================================================================
        //This code was found at https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects
        //is the answer provided by nightcoder.  This solution seems to be the only one that actually clears the Excel instance out of the 
        //Processes in Windows Task Manager.  The idea is to completely shut down Excel so that I can delete the original spreadsheet.  So far not
        //working out so well.
        private void GenerateWorkbook()
        {
          try
          {
              GetExcel();
          }
          finally
          {
            GC.Collect();
            GC.WaitForPendingFinalizers();
          }
        }

        //=============================================================================================================================================
        ///<summary> Tries to find and kill process by hWnd to the main window of the process.</summary>
        ///<param name="hWnd">Handle to the main window of the process.</param>
        ///<returns>True if process was found and killed. False if process was not found by hWnd or if it could not be killed.</returns>
        public static bool TryKillProcessByMainWindowHwnd(int hWnd)
        {
            uint processID;
            GetWindowThreadProcessId((IntPtr)hWnd, out processID);
            if (processID == 0) return false;
            try
            {
                Process.GetProcessById((int)processID).Kill();
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (Win32Exception)
            {
                return false;
            }
            catch (NotSupportedException)
            {
                return false;
            }
            catch (InvalidOperationException)
            {
                return false;
            }
            return true;
        }

        ///<summary> Finds and kills process by hWnd to the main window of the process.</summary>
        ///<param name="hWnd">Handle to the main window of the process.</param>
        ///<exception cref="ArgumentException">
        ///Thrown when process is not found by the hWnd parameter (the process is not running). 
        ///The identifier of the process might be expired.
        ///</exception>
        ///<exception cref="Win32Exception">See Process.Kill() exceptions documentation.</exception>
        ///<exception cref="NotSupportedException">See Process.Kill() exceptions documentation.</exception>
        ///<exception cref="InvalidOperationException">See Process.Kill() exceptions documentation.</exception>
        public static void KillProcessByMainWindowHwnd(int hWnd)
        {
            uint processID;
            GetWindowThreadProcessId((IntPtr)hWnd, out processID);
            if (processID == 0)
                throw new ArgumentException("Process has not been found by the given main window handle.", "hWnd");
            Process.GetProcessById((int)processID).Kill();
        }
        //=========================================================================================================================================
        //=========================================================================================================================================
        //=========================================================================================================================================
    }
}
Schreibe einen Kommentar