且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不传递文件名的情况下创建新的Excel文件并使用C#复制某些数据

更新时间:2023-09-21 08:30:58

您无法在没有文件路径的情况下打开新的Excel文件,但是您可以创建新的Excel文件并将数据写入其中。两者都有所不同。另请注意,您始终需要提供打开文件的文件路径才能正常工作。



本文可能会帮助您使用Excel使用C#,使用C#使用Excel [ ^ ]
You cannot Open a new Excel file without file path, however you can create a new Excel file and write the data to it. There is a difference in both. Also note that you will always require to provide file path to open the file for working.

This article might help you to work with Excel using C#, Working with Excel Using C#[^]


private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            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);

            MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }