在C#中阅读Excel电子表格

时间:2017-07-19 00:49:17

标签: c# excel datagridview page-setup

我制作了一个打开Excel文件的程序。

存在数据页面和空白页面。 我是否只能在组合框中添加数据所在的页面? 我可以使用ButtonEvent仅查看包含数据的页面吗?

        string filePath = openFileDialog1.FileName;//파일 경로 가져오기
        string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
        string fileExtension = Path.GetExtension(filePath);

        //string connectionString = string.Empty;
        string sheetName = string.Empty;

     using (OleDbConnection con = new OleDbConnection(ConnectStr()))
        {
            using (OleDbCommand cmd = new OleDbCommand())
            {
                using (OleDbDataAdapter oda = new OleDbDataAdapter())
                {
                    DataTable dt = new DataTable();

                    cmd.CommandText = "SELECT * From [" + sheetName + "]";
                    cmd.Connection = con;
                    con.Open();
                    oda.SelectCommand = cmd;
                    oda.Fill(dt);
                    con.Close();

                    dataGridView1.DataSource = dt; 

                }
            }
        }

 public string ConnectStr()
    {
        string filePath = openFileDialog1.FileName;
        string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
        string fileExtension = Path.GetExtension(filePath);

        string connectionString = string.Empty;
        string sheetName = string.Empty;

        switch (fileExtension)
        {
            case ".xls":    //Excel 97-03버전

                connectionString = string.Format(Excel03ConString, filePath); 
                break;
            case ".xlsx":  //Excel 07이상 버전
                connectionString = string.Format(Excel16ConString, filePath);
                break;
        }
        return connectionString;
    }

1 个答案:

答案 0 :(得分:0)

我真的不知道这是什么。但是我请求你只需要显示电子表格中的特定表格,如果我错了,请更正。

有一个SQL推荐我们可以从特定工作表中查询。

try
            {
                this.txtImportFilePath.Text = opd.FileName;
                OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");

                StringBuilder stbQuery = new StringBuilder();
                stbQuery.Append("Select * From [Sheet1$]");
                OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);

                DataSet dsXLS = new DataSet();
                adp.Fill(dsXLS);

                DataView dvEmp = new DataView(dsXLS.Tables[0]);

                trnxlistDataview.DataSource = dvEmp;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }