将上传的文件类型转换为Datatable

时间:2013-11-23 11:02:14

标签: c# asp.net

您好我有以下代码上传excel文件并显示行。

if (fileExtension == ".xls")
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                //    lblMessage.Text = "Only files with .xlsx or .xls extensions are allowed";
                //    lblMessage.ForeColor = System.Drawing.Color.Red;


            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
            Datatable dtExcelRecords = new Datatable();
            con.Open();
            Datatable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
            cmd.CommandText = "SELECT * FROM[" + getExcelSheetName + "]";
            dAdapter.SelectCommand = cmd;
            dAdapter.Fill(dtExcelRecords);
            con.Close();

            GridView1.DataSource = dtExcelRecords;
            GridView1.DataBind();

在下一行

 Datatable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

我收到编译错误

Error   36  Cannot implicitly convert type 'System.Data.DataTable' to 'Datatable'

请告诉我如何修复它。 谢谢

2 个答案:

答案 0 :(得分:0)

  if (filenam.ToString() == ".xls")
  { constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; }
  else if (filenam.ToString() == ".xlsx")
  { constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; }
  else { Response.Write("<script>alert('Load Excel file Only')</script>"); }
  string Qry = "SELECT [Customer], [Project], [Contact], [Designation], [Phone], [EmailID],[Region] FROM [Sheet1$]";
  OleDbConnection conn = new OleDbConnection(constr);
  if (conn.State == ConnectionState.Closed)
  {
  conn.Open();
  OleDbCommand cmd = new OleDbCommand(Qry, conn);
  OleDbDataAdapter da = new OleDbDataAdapter();
  da.SelectCommand = cmd;
  DataTable dt = new DataTable();
  da.Fill(dt);
  if (dt != null && dt.Rows.Count > 0)
  {
  gv_upload.DataSource = dt;
  gv_upload.DataBind();
  }
  da.Dispose(); conn.Close(); conn.Dispose();
  }

这是工作代码试试吧

答案 1 :(得分:0)

C#区分大小写。 DatatableDataTable不同 具有大写的版本是正确的。

您需要修复所有DataTable声明

DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);