将Excel文件加载到DataTable或DateSet的C#方法

时间:2018-12-07 15:14:36

标签: c#

下午好, 我正在尝试创建一种方法,该方法返回Excel文件的数据以通过FileDialog进行调用,例如...这是我的代码:

public static DataSet MtdGetExcel(string prtlocalFile)
        {
            string sDBstrExcel = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=0\"", prtlocalFile);

            OleDbConnection conexaoExcel = new OleDbConnection(sDBstrExcel);
            conexaoExcel.Open();
            DataTable dt = conexaoExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            DataSet output = new DataSet();
            foreach (DataRow row in dt.Rows)
            {
                 string sheet = row["TABLE_NAME"].ToString();    //Obtém o nome da planilha corrente
                 OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conexaoExcel); //Obtém todas linhas da planilha corrente
                 cmd.CommandType = CommandType.Text;
                 DataTable outputTable = new DataTable(sheet);   //Copia os dados da planilha para o DataTable
                 output.Tables.Add(outputTable);
                 new OleDbDataAdapter(cmd).Fill(outputTable);
            }
            conexaoExcel.Close();

            return output;
        }

但是当我调用该方法时,它不会在DataGridView中返回任何内容...

public void testeImportExcel()
        {
            try
            {
                OpenFileDialog fdlg = new OpenFileDialog();
                fdlg.Title = "Selecione o relatório do Detran";
                fdlg.InitialDirectory = @"c:\";
                //string endereco = fdlg.FileName;
                //txtNomeArquivo.Text = fdlg.FileName;
                fdlg.Filter = "Excel File (*.xlsx)|*.xlsx";
                //fdlg.Filter = "Excel File (*.csv)|*.csv";
                fdlg.FilterIndex = 1;
                fdlg.RestoreDirectory = true;
                if (fdlg.ShowDialog() == DialogResult.OK)
                {
                    myDtGridView.DataSource = MtdGetExcel(fdlg.FileName);
                    myDtGridView.AutoGenerateColumns = true;
                }

             }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

结果:

enter image description here

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

这是我在生产中使用的确切方法:

    public DataTable ReadExcel(string fileName, string TableName)
    {
        DataTable dt = new DataTable();

        OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + TableName, conn);


        try
        {
            conn.Open();
            OleDbDataReader reader = cmd.ExecuteReader();

            while (!reader.IsClosed)
            {
                dt.Load(reader);
            }
        }
        finally
        {
            conn.Close();
        }

        return dt;
    }

我敢肯定,只要查看一下就可以知道-该方法将要读取的Excel的fileName(或文件路径)作为文件名。创建连接字符串和命令。 Excel将像数据库一样被读取,其工作表将像表一样被读取。 TableName是工作表(表)的名称。此方法返回一个DataTable,可以根据需要将其添加到DataSet中。