简体   繁体   中英

How to read a specific sheet in an Excel file using Microsoft.Office.Interop.Excel

I want to read a specific sheet in an excel file using "Microsoft.Office.Interop.Excel" . My code goes like

    private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
    private static Workbook newWorkbook = null;
    private static _Worksheet objsheet = null;

    static void excel_init(String path)
    {
        appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();

        if (System.IO.File.Exists(path))
        {
                newWorkbook = appExcel.Workbooks.Open(path, true, true);
                objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;               
        }
        else
        {
            MessageBox.Show("Unable to open file!");               
        }
    }

How to alter this for read a specific sheet?

You Should Try this way :

static void Main(string[] args)
            {
                try
                {

                    OleDbConnection oledbConn;

                    string path = System.IO.Path.GetFullPath(@"D:\FileName.XLS");

                    oledbConn = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" +
                            path + "';Extended Properties=Excel 8.0;");

                    oledbConn.Open();
                    OleDbCommand cmd = new OleDbCommand(); ;
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    DataSet ds = new DataSet();


                    cmd.Connection = oledbConn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM [sheet2]";
                    oleda = new OleDbDataAdapter(cmd);
                    oleda.Fill(ds, "dsSlno");
                    oledbConn.Close();

                }
                catch (Exception)
                {

                    throw;
                }

            }

like below

var sheet = (_Worksheet)appExcel.ActiveWorkbook.Sheets["Sheet2"];
sheet.Select(Type.Missing);

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