无法在c#中读取导出的xls文件

时间:2014-12-11 10:13:51

标签: c#

首先我导出gridviewdata到excel格式然后我导入相同的导出excel wthout保存错误发生(外部表不是预期的格式) 但是我保存了它工作的同一个文件。

下面用于导出gridview to excel的代码

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    gvopp.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();

在要使用的代码下导入Excel文件

   if (Extension == ".xls")
    {
        conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath +
                    ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
    }
    else if (Extension == ".xlsx")
    {

        conStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FilePath+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";";
    }


    conStr = String.Format(conStr, FilePath, isHDR);

    OleDbConnection connExcel = new OleDbConnection(conStr);

    OleDbCommand cmdExcel = new OleDbCommand();

    OleDbDataAdapter oda = new OleDbDataAdapter();

    DataTable dt = new DataTable();
    DataTable dtid = new DataTable();

    cmdExcel.Connection = connExcel;

    //Get the name of First Sheet

  connExcel.Open();

    DataTable dtExcelSchema;

    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
    connExcel.Close();`

请解决这个问题。

0 个答案:

没有答案