【问题标题】:Excel cannot read the data after i download itExcel 下载后无法读取数据
【发布时间】:2020-12-08 10:07:06
【问题描述】:

我正在尝试下载我为其提供正确路径的 excel 文件。但是当我尝试打开时下载它后,我得到了错误

excel 无法打开文件,因为文件格式或文件扩展名无效。验证文件是否已损坏...

在这个分开的类中,我创建了导出函数来创建和写入数据到 excel 文件中

        public static ExcelPackage ExportExcel(string fileName, decimal projectId, ModelContext context)
    {
        ExcelPackage pck = new ExcelPackage();
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Project");
        

        var surveys = context.Survey.Where(x => x.ProjectId == projectId)
            .Include(s=> s.Question);
        


        #region datatable

        

        

        ws.Cells["A1"].Value = "SURVEY_ID";
        ws.Cells["B1"].Value = "PAGE";
        ws.Cells["C1"].Value = "RANKING";
        ws.Cells["D1"].Value = "PARENT_ID";
        ws.Cells["E1"].Value = "ID";
        ws.Cells["F1"].Value = "ITEMTYPE";
        ws.Cells["G1"].Value = "CONTROLTYPE";
        ws.Cells["H1"].Value = "DISPLAYTYPE";
        ws.Cells["J1"].Value = "VARIABLE_DESCRIPTION";
        ws.Cells["K1"].Value = "VARIABLE_NAME";
        ws.Cells["L1"].Value = "VARIABLE_LABEL";
        ws.Cells["M1"].Value = "VALUE_LABEL_ID";
        ws.Cells["N1"].Value = "MISSING_VALUE_ID";
        ws.Cells["O1"].Value = "IS_REQUIRED";
        ws.Cells["P1"].Value = "DATA_TYPE";
        ws.Cells["Q1"].Value = "VARIABLE_LENGTH";
        ws.Cells["R1"].Value = "NR_OF_DECIMALS";
        ws.Cells["S1"].Value = "COMMENT";
        ws.Cells["T1"].Value = "COMMENT_TYPE";
        ws.Cells["U1"].Value = "SHOW_ALL_FOR_STUDY";
        ws.Cells["V1"].Value = "ANSWER_FONT";
        ws.Cells["W1"].Value = "IS_DELETE_QUESTION";
        ws.Cells["X1"].Value = "IS_STOP_QUESTION";
        ws.Cells["Y1"].Value = "ROUTING_TYPE";
        ws.Cells["Z1"].Value = "ROUTING_VALUE";
        ws.Cells["AA1"].Value = "SHOW";

        int rowStart = 2;
        foreach (var survey in surveys)
        {

            foreach (var item in survey.Question)
            {
                ws.Cells[String.Format("A{0}", rowStart)].Value = survey.IdSurvey;
                ws.Cells[String.Format("B{0}", rowStart)].Value = item.Page;
                ws.Cells[String.Format("C{0}", rowStart)].Value = item.Ranking;
                ws.Cells[String.Format("D{0}", rowStart)].Value = item.ParentId;
                ws.Cells[String.Format("E{0}", rowStart)].Value = item.IdQuestion;
                ws.Cells[String.Format("F{0}", rowStart)].Value = item.Itemtype;
                ws.Cells[String.Format("G{0}", rowStart)].Value = item.Controltype;
                ws.Cells[String.Format("H{0}", rowStart)].Value = item.Displaytype;
                ws.Cells[String.Format("J{0}", rowStart)].Value = item.VariableDescription;
                ws.Cells[String.Format("K{0}", rowStart)].Value = item.VariableName;
                ws.Cells[String.Format("L{0}", rowStart)].Value = item.VariableLabel;
                ws.Cells[String.Format("M{0}", rowStart)].Value = item.ValueLabelId;
                ws.Cells[String.Format("N{0}", rowStart)].Value = item.MissingValueId;
                ws.Cells[String.Format("O{0}", rowStart)].Value = item.IsRequired;
                ws.Cells[String.Format("P{0}", rowStart)].Value = item.DataType;
                ws.Cells[String.Format("Q{0}", rowStart)].Value = item.VariableLength;
                ws.Cells[String.Format("R{0}", rowStart)].Value = item.NrOfDecimals;
                ws.Cells[String.Format("S{0}", rowStart)].Value = item.Comment;
                ws.Cells[String.Format("T{0}", rowStart)].Value = item.CommentType;
                ws.Cells[String.Format("U{0}", rowStart)].Value = item.ShowAllForStudy;
                ws.Cells[String.Format("V{0}", rowStart)].Value = item.AnswerFont;
                ws.Cells[String.Format("W{0}", rowStart)].Value = item.IsDeleteQuestion;
                ws.Cells[String.Format("X{0}", rowStart)].Value = item.IsStopQuestion;
                ws.Cells[String.Format("Y{0}", rowStart)].Value = item.RoutingType;
                ws.Cells[String.Format("Z{0}", rowStart)].Value = item.RoutingValue;
                ws.Cells[String.Format("AA{0}", rowStart)].Value = item.Show;
                rowStart++;
            }
            
            ws.Cells["A:AZ"].AutoFitColumns();
            


        }
        #endregion

        return pck;

    }
}

然后我从控制器调用这个函数:

      [HttpGet("{Id}")]
    public IActionResult Export(IFormCollection form, decimal? id)
    {

        var exportId = _context.Project.First(x => x.ProjectId == id).ProjectId;
        var fileName = form["Codebook.xlsx"];

        //var pck = Models.Export.ExportExcel(fileName, exportId, _context);
        return File(Models.Export.ExportExcel(fileName, exportId, _context).Stream
            , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Codebook.xlsx");

【问题讨论】:

  • 如果您使用Load 方法之一,例如ws.Cells.LoadFromCollection(questions),您可以避免大部分代码。您可以使用.SelectMany(s=>s.Question) 从调查中获取问题。在这种情况下不需要Include()
  • 至于主要问题,您必须确保流的Position 为0。从流中读取从Position 开始。写入后,流的位置在流的末尾,从它读取不会读取任何内容
  • @Panagiotis Kanavos 至于第一个建议真的很方便!!因为主要问题是应用程序只能看到一个目录,无论我尝试什么,他都没有改变它,所以我得到的错误是他无法找到我给出的目录,尽管我通过了一个根目录。
  • 不,问题是在写入 Position 之后,读取开始是流的结尾。您需要将其设置为 0:pck.Stream.Position=0;。读取和写入流都从Position 开始。读取和写入都将位置移动已读取或写入的字节数。如果要读取整个文件,需要将Position移动到0

标签: c# excel asp.net-core model-view-controller


【解决方案1】:

我不知道它是否重要:我们使用与您相同的内容类型,但我们将 ContentEncoding 设置为 System.Text.Encoding.UTF8。简化代码:

public System.Web.Mvc.ActionResult Export(string filename)
{
            Response.AppendHeader("Content-Disposition", string.Format("attachment; filename*=UTF-8''{0}", Uri.EscapeDataString(filename)));
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Stream ms = <<Excel file content>>
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

【讨论】:

    【解决方案2】:

    文件应先保存在 webroot 中,然后以字节数组的形式返回 所以在控制器添加 IwebHostEnviroment 然后更新操作方法

            public IActionResult Export(IFormCollection form, decimal? id)
        {
            var project = _context.Project.First(x => x.ProjectId == id).ProjectId;
            var fileName = form["Codeboek"];
            var pck = Models.Export.ExportExcel(fileName, project, _context);
    
            var contentRootPath = _env.ContentRootPath;
            fileName = "exportFile.xlsx";
            
            
            var filePath = contentRootPath + "/" + fileName;
            pck.SaveAs(new FileInfo(filePath));
            byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
    
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多