【问题标题】:Find the Empty excel file when upload to datatable上传到数据表时找到空的excel文件
【发布时间】:2012-11-16 06:26:50
【问题描述】:

用户通过 Excel 文件上传输入。 我想发现 excel 文件是空的,否则。我检查内容长度和文件大小以查找空文件。大小因空文件而异(没有类型和用户类型数据,并删除所有数据以使其为空)对于空文件 8714 的示例内容长度,但用户键入任何数据并删除所有数据,则内容长度为 8104,就像这样

所以我将excel文件转换为数据表并检查数据表是否为空。当将空文件转换为数据表时,数据表有默认列F1。所以数据表=null不起作用。请帮助我

我的代码:

string dirpath = Server.MapPath("~") + "uploadfile\\";
                string LocalFilePath = dirpath + fileName;
                fileUpload.PostedFile.SaveAs(LocalFilePath);

                string fileType = Path.GetExtension(fileName);        
                string SourceConstr = string.Empty;
                var Inputs = ProjectAttributeMasterService.GetInputAttributes(7);

                if (fileType == ".xls" || fileType == ".xlsx")
                {



                    if (fileType == ".xls")
                    {
                        SourceConstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + LocalFilePath + "';;Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";

                    }


                    OleDbConnection con = new OleDbConnection(SourceConstr);
                    con.ResetState();
                    con.Open();

                    System.Data.DataTable dtl = new DataTable();
                    System.Data.DataTable dts = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
                    da.Fill(dtl);


                    if ((dtl.Rows.Count >= 1 || dtl.Columns.Count >= 1) && !dtl.Columns.Contains("F1")){
            }
          else
          {
         /empty file
          }

dtl.Columns.Contains("F1")..如果我使用这种条件,即使 Excel 在单元格“F1”中包含数据,则返回 Empty..并且 F1 不是所有服务器的默认列...所以它也是不好。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    使用代码如下:

         OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
         da.Fill(ds);
        if ((ds.Table.Count >= 1)
         {    
              if (ds.Tables[0].Rows.Count > 0)
              {
                 //Excel contains data
              }
              else
              {
                 //file is empty
              }   
         }
         else
         {
           //file is empty
         }
    

    【讨论】:

    • 数据表不包含 Table 方法。在 (dtl.Table ) 中出现错误
    • 嗨 Priya 我编辑代码并使用数据集代替数据表尝试使用这种方式..
    • 或者只检查数据表中大于 0 的行会像 if (dtl.Rows.Count > 0){data exists} else{not exist}
    猜你喜欢
    • 2013-12-24
    • 1970-01-01
    • 2019-12-24
    • 2020-11-11
    • 2017-02-12
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多