上载xls格式档案时,asp.net C#中出现错误

时间:2018-08-01 13:09:05

标签: c# asp.net excel

我想上传.xls.xlsx格式的文件。 .xlsx格式工作正常,但是在上传.xls时出现错误信息

  

外部表的格式不正确

这是我尝试过的代码

if (fluploadData.HasFile)
    {

        string filename = Path.GetFileName(fluploadData.FileName);
        // FileUpload.SaveAs(Server.MapPath("~/") + filename);
        string filenamewithoutrext = string.Empty;
        FileExt = Path.GetExtension(fluploadData.FileName).ToLower();
        if (Path.GetExtension(fluploadData.FileName).ToLower() != ".xls" &&
            Path.GetExtension(fluploadData.FileName).ToLower() != ".xlsx"
        )
        {

            Response.Write("Only .xls, .xlsx are allowed.!");
            return;
        }

        filenamewithoutrext = Path.GetFileNameWithoutExtension(fluploadData.FileName).ToLower();

        string path = Server.MapPath("UploadData\\");
        string filename_ = filenamewithoutrext;

        //   DeleteDirectory(path);
        if (!Directory.Exists(path))   // CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER.
        {
            Directory.CreateDirectory(path);
        }
        else
        {
            foreach (string file in Directory.GetFiles(path))
            {
                File.Delete(file);
            }
        }

        string fname;
        fname = path + filename_ + ".xls";

        fluploadData.SaveAs(fname);
        HttpContext.Current.Session["ExcelFilePath"] = fname;

        string conStr = "";
        System.Data.DataTable dtExcelRows = new System.Data.DataTable();

        switch (FileExt)
        {
            case ".xls": //Excel 97-03
                conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07
                conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
        }

        conStr = String.Format(conStr, fname, "YES");

        System.Data.OleDb.OleDbConnection connExcel = new System.Data.OleDb.OleDbConnection(conStr);
        System.Data.OleDb.OleDbCommand cmdExcel = new System.Data.OleDb.OleDbCommand();
        System.Data.OleDb.OleDbDataAdapter oda = new System.Data.OleDb.OleDbDataAdapter();
        cmdExcel.Connection = connExcel;


        connExcel.Open(); // here is coming the error

        System.Data.DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
        System.Data.DataTable dtExcelColumnsTable = connExcel.GetSchema("Columns");
        //string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString().Replace('\'', ' ').Trim();
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString().Replace('\'', ' ').Trim();  // nadeem
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
        oda.SelectCommand = cmdExcel;
        oda.Fill(dtExcelRows);
        connExcel.Close();
        bool Structure_FLG = false;
}

还在下面的web.config中正确设置了连接字符串

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1}'"/>

我在哪里做错了?

1 个答案:

答案 0 :(得分:1)

此行会将所有上传的文件保存为XLS格式,而不考虑上传的文件扩展名,并且在实际文件格式不匹配时可能会引发异常:

fname = path + filename_ + ".xls";

我建议使用Path.GetExtension(fluploadData.FileName)方法提供的文件扩展名:

string fname = path + filename_ + FileExt;

外部表不是预期的格式当尝试使用使用Jet OLEDB 4.0提供程序的连接字符串读取较新的XLSX格式时,通常会发生错误,反之亦然,因此请确保已设置proper connection string与上传的文件扩展名相对应。