Embed excel sheet in C# user control

后端 未结 3 1461
悲哀的现实
悲哀的现实 2020-12-21 00:21

I need to embed an excel sheet portion (not the whole sheet) in a user control in C# language. And I want to manipulate the data on it and save it in a collection.

3条回答
  •  不知归路
    2020-12-21 00:51

    I would open the spreadsheet with the Excel COM Library. If you add a reference to the Microsoft Excel Object Library, you can get to the Com interface.

    Add these using statements:

    using Microsoft.Office.Interop;
    using Microsoft.Office.Interop.Excel;
    

    Then you can read from the spreadsheet by doing something like this:

       private void GetData(string fileName, string tabName)
        {
            Workbook theWorkbook;
    
            Application ExcelObj = null;
            ExcelObj = new Application();
    
            theWorkbook = ExcelObj.Workbooks.Open(fileName,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
    
    
            Sheets sheets = theWorkbook.Worksheets;
            Worksheet worksheet = (Worksheet)sheets[tabName];
    
            Range range = worksheet.get_Range("A1:A1", Type.Missing);
    
            string data = range.Text as string;
    
            //
            // TODO : store the data
            //
    
            theWorkbook.Close(false, fileName, null);
        }
    

    This code would read the contents of the A1 cell into a string.

    One of the quirks of working with the Excel COM interface is that you have to access data in a Range, even if you just want one cell. You can set the range to be a group of cells, then you can iterate over the collection that it returns to get the contents of each cell.

    You would also want to add some error checking/handling on the file name and tab name.

    There is also a way to use ODBC to read from Excel, but the spreadsheet has to be formatted in a certain way. There has to be a header data in row 1. I've found it easier to use the COM interface.

    Once you have acquired the data you need, you could put it into a typed DataSet. Then you could bind that dataset to a DataGridView if you're using WinForms or a ListBox in WPF. If you just want to save the data in an XML format, you could use the DataSet WriteXml function to store the data to a file.

提交回复
热议问题