【问题标题】:Excel cannot open the file because the file format or file extension is not valid. Verify that file has not been corruptedExcel 无法打开文件,因为文件格式或文件扩展名无效。确认文件没有损坏
【发布时间】:2018-12-14 06:09:34
【问题描述】:

我正在尝试使用xlsxxls 格式导出到excel,但在尝试打开文件时出现此错误。 Excel 无法打开文件 'tms.xlsx',因为文件格式或文件扩展名无效。验证文件没有损坏并且文件扩展名与文件格式匹配。

public static void ExportToExcel(object allLists, string fileName, string driverName)
        {
            try
            {

                grid.DataSource = allLists;
                grid.DataBind();
                RowCreated();
                Header(fileName, driverName);
                HttpContext.Current.Response.ClearContent();
                string FileName = String.Format(fileName + "-{0}", DateTime.Now.ToString("dd/MMM/yyyy"));               
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                //Applying style to grid view header cells


                for (int  i = 0; i < grid.Rows.Count; i++)
                {
                    for (int J = 0; J < grid.HeaderRow.Cells.Count; J++)
                    {
                        if ((grid.Rows[i].Cells[J].Text.Contains("-y@llow")))
                        {
                            grid.Rows[i].Cells[J].BackColor = System.Drawing.Color.FromArgb(255, 255, 179);
                            var val = Convert.ToString(grid.Rows[i].Cells[J].Text);
                            if (val != null && val != "")
                            {
                                if (val.Contains("-y@llow"))
                                {
                                    val = val.Replace("-y@llow", "");
                                    grid.Rows[i].Cells[J].Text =Convert.ToString(val);
                                }
                            }
                        }
                        else if((grid.Rows[i].Cells[J].Text.Contains("-gr@en")))
                           
                        {
                            grid.Rows[i].Cells[J].BackColor = System.Drawing.Color.FromArgb(159, 223, 159);
                            var val =Convert.ToString(grid.Rows[i].Cells[J].Text);
                            if (val != null && val != "")
                            {
                                if (val.Contains("-gr@en"))
                                {
                                    val = val.Replace("-gr@en", "");
                                    grid.Rows[i].Cells[J].Text = Convert.ToString(val);
                                }
                            }
                            
                        }
                    }
                }
                for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
                {

                    grid.HeaderRow.Cells[i].Style.Add("background-color", "#337ab7");
                    grid.HeaderRow.Cells[i].Style.Add("color", "white");
                  
                }

                grid.RenderControl(htw);
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
            catch (Exception)
            {
                //Response.End() will generate exception so, do not throw the exception here.
                //Response.Write(Ex.StackTrace);
            }
        }

【问题讨论】:

  • 你创建excel文件的地方在哪里?
  • 我用c#写代码。
  • 我从 c# 代码生成 excel 文件。
  • 那部分在哪里?当您将该对象转换为响应时?
  • 您发送的 HTML 表格是否伪装成 Excel 文件?这曾经可以工作,但在较新版本的 Office 中,有防止这样做的“保护”。谷歌“扩展强化” - 例如jwgoerlich.com/excel-extension-hardening-and-web-applications

标签: c# excel


【解决方案1】:

请检查内容类型和扩展名。您目前拥有.xlsapplication/vnd.ms-excel。声明的xlsx需要相应的扩展名和

ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"`

为了添加一些上下文,我在一个返回ActionResult的控制器方法中使用它,如下所示

ActionResult ExportAsExcel(object input)
{
    var fileData = ExcelExport.CreateExcelContent(input);

    if (fileData == null || fileData.Length == 0)
    {
        ViewData["Message"] = "Could not create export file";
        View("Error");
    }

    // File is of type Controller.File
    return File(fileData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx");
}

【讨论】:

  • 无法使用此代码:ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"`
  • 这段代码:HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xlsx"); HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  • 嗯,也许是内容吧。请使用@cdev 已经提出的相应代码更新您的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2023-01-19
  • 2020-07-11
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多