将具有正确工作表名称的Excel文件上传到我的Windows窗体应用程序dataGridview中

时间:2018-06-26 05:52:38

标签: c# asp.net

我正在使用下面的代码将excel文件上传到Windows窗体应用程序上的dataGridview中。 剩下的唯一问题是,我必须对工作表名称进行硬编码才能使其上载并显示在我的datagridview上。我想知道此问题的解决方法,因此我不必对工作表名称进行硬编码。

代码行:OleDbDataAdapter oda =新的OleDbDataAdapter(string.Format(“ select * from [sheet $]”),cnnxls);

注意:[sheet $]是硬编码的,因此我可以查看我的excel文件的当前表。请帮助我,这样我就可以在不对工作表名称进行硬编码的情况下执行此操作,这样它就可以自动检测到它。

private void btnLoad_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();  //create openfileDialog Object
        openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx| 
        openFileDialog1.FilterIndex = 3;

        openFileDialog1.Multiselect = false;        //not allow multiline selection at the file selection level
        openFileDialog1.Title = "Open Text File-R13";   //define the name of openfileDialog
        openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory

        if (openFileDialog1.ShowDialog() == DialogResult.OK)        //executing when file open
        {
            string pathName = openFileDialog1.FileName;
            var fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
            DataTable tbContainer = new DataTable();
            string strConn = string.Empty;
            string sheetName = fileName;

            FileInfo file = new FileInfo(pathName);
            if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
            string extension = file.Extension;
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [Sheet$]"), cnnxls);
            oda.Fill(tbContainer);

            dataGridView2.DataSource = tbContainer;
        }

    }
    catch (Exception ec)
    {
        MessageBox.Show(ec.Message);
    }
}

0 个答案:

没有答案