-4

我做了一个程序来打开 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;
    }
4

1 回答 1

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);
            }
于 2017-07-19T03:04:44.923 回答