如何使用Microsoft.Office.Interop.Excel读取Excel文件中的特定工作表

本文关键字:Excel 工作 读取 Microsoft 何使用 Office Interop 文件 | 更新日期: 2023-09-27 18:16:05

我想使用"Microsoft.Office.Interop.Excel"读取excel文件中的特定工作表。我的代码像

    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!");               
        }
    }

如何为阅读特定的表格更改此设置?

如何使用Microsoft.Office.Interop.Excel读取Excel文件中的特定工作表

你应该试试这样做:

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;
                }
            }

类似下面

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