简体   繁体   中英

Is it possible to import data from Excel through memory?

Say a new Excel file is opened and data is entered into it. Could an external C# application hook onto the Excel process and get the data from it? Also, the Excel file is never saved into a file.

Would this be difficult to do and also could you point me in the right direction on how to achieve this.

Just add this code in the code behind of a windows form application that has a button named "button1" added on it. This sample code will iterate through cells of the Excel file and display the content of each cell in a Message Box. Of course a project reference to "Microsoft.Office.Interop.Excel" is required.

And don't forget to actually create the excel file, in this example I used this path "C:\\ExcelData\\DataToImp.xlsx".

using Excel = Microsoft.Office.Interop.Excel;


    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        string str;
        int rCnt = 0;
        int cCnt = 0;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open("C:\\ExcelData\\DataToImp.xlsx", 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);

        range = xlWorkSheet.UsedRange;

        for (int rowIndex = 1; rowIndex <= range.Rows.Count; rowIndex++)
        {
            for (int columnIndex = 1; columnIndex <= range.Columns.Count; columnIndex++)
            {
                Excel.Range rangeTest = range.Cells[rowIndex, columnIndex] as Excel.Range;

                if (rangeTest.MergeCells)// && rangeTest.Value2 == null)
                {
                    //continue;

                    int columns = rangeTest.Columns.Count;
                    columnIndex += columns;
                }

                MessageBox.Show("m " + (string)rangeTest.Value2);

            }
        }

        xlWorkBook.Close(true, null, null);
        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();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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