【问题标题】:Excel spreadsheet generation results in "different file format than extension error" when opening in excel 2007在 excel 2007 中打开时,Excel 电子表格生成导致“文件格式与扩展名错误不同”
【发布时间】:2010-10-13 17:38:51
【问题描述】:

电子表格仍会显示,但会显示警告消息。出现这个问题的原因似乎是 Excel 2007 对匹配其扩展名的格式比早期版本的 Excel 更加挑剔。

该问题最初是由 ASP.Net 程序发现的,并在 Excel 错误中产生“您尝试打开的文件,”Spreadsheet.aspx-18.xls',格式与文件扩展名指定的格式不同.验证...”。但是,当我打开文件时,它显示得很好。我使用的是 Excel 2007。Firefox 将文件识别为 Excel 97-2003 工作表。

这是一个产生问题的 ASP.NET 页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Spreadsheet.aspx.cs" Inherits="Spreadsheet" %>

文件后面的代码如下:

public partial class Spreadsheet : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "application/vnd.ms-excel";
        Response.Clear();
        Response.Write("Field\tValue\tCount\n");

        Response.Write("Coin\tPenny\t443\n");
        Response.Write("Coin\tNickel\t99\n"); 

    } 

}

T

【问题讨论】:

标签: c# excel webforms xls


【解决方案1】:

我更喜欢使用 Grid 并更改响应类型,我还没有遇到过这种方法的问题。我没有使用直接制表符分隔的文件。一种可能性是\n 可能必须是\r\n。只是盲目的射击。

【讨论】:

    【解决方案2】:

    使用

    content-type=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

    并将扩展名指定为 xlsx

    【讨论】:

      【解决方案3】:

      http://blogs.msdn.com/vsofficedeveloper/pages/Excel-2007-Extension-Warning.aspx

      这是一个链接,基本上描述了 MS 知道您描述的问题,并且无法从 ASP.NET 代码中抑制它。它必须在客户端的注册表中被禁止/修复。

      【讨论】:

      • 我遇到过,就是这个问题。
      • 本文还提供了另一个修复,它不涉及修改注册表。我添加了这一行: Response.AddHeader("Content-Disposition", "Attachment;Filename=Spreadsheet.csv");然后生成一个逗号分隔的文件。我可以使用带有 .txt 文件的选项卡。
      • 进一步了解 Jeff Bloom,如果您的输出是 excel as xml,请在下面查看我的答案
      • 我在哪里可以找到在客户注册表上解决此问题的方法?
      【解决方案4】:

      如果您像我一样将 Excel 工作表生成为 2003 XML 文档,则可以通过执行以下操作来删除警告:

      添加到 XML 输出:

      <?xml version="1.0" encoding="utf-16"?>
        <?mso-application progid="Excel.Sheet"?>
        ...
      

      添加到下载页面:

      // Properly outputs the xml file
      response.ContentType = "text/xml";
      
      // This header forces the file to download to disk
      response.AddHeader("content-disposition", "attachment; filename=foobar.xml");
      

      现在 Excel 2007 将不会显示文件内容和文件扩展名不匹配的警告。

      【讨论】:

      • @BombDefused 它应该使用 excel 自动打开。如果您有 excel > 2003 的版本,&lt;?mso-application progid="Excel.Sheet"?&gt; 行将有助于实现这一点。如果它不起作用,可能是因为文件关联或 Excel 设置。
      【解决方案5】:

      我已经看到这个问题被问过很多次了。我今天遇到了同样的困难,所以我使用 NPOI npoi.codeplex.com/ 解决了这个问题

      public static class ExcelExtensions
      {
          /// <summary>
          /// Creates an Excel document from any IEnumerable returns a memory stream
          /// </summary>
          /// <param name="rows">IEnumerable that will be converted into an Excel worksheet</param>
          /// <param name="sheetName">Name of the Ecel Sheet</param>
          /// <returns></returns>
          public static FileStreamResult ToExcel(this IEnumerable<object> rows, string sheetName)
          {
              // Create a new workbook and a sheet named by the sheetName variable
              var workbook = new HSSFWorkbook();
              var sheet = workbook.CreateSheet(sheetName);
      
              //these indexes will be used to track to coordinates of data in our IEnumerable
              var rowIndex = 0;
              var cellIndex = 0;
      
              var excelRow = sheet.CreateRow(rowIndex);
      
              //Get a collection of names for the header by grabbing the name field of the display attribute
              var headerRow = from p in rows.First().GetType().GetProperties()
                              select rows.First().GetAttributeFrom<DisplayAttribute>(p.Name).Name;
      
      
              //Add headers to the file
              foreach (string header in headerRow)
              {
                  excelRow.CreateCell(cellIndex).SetCellValue(header);
                  cellIndex++;
              }
      
              //reset the cells and go to the next row
              cellIndex = 0;
              rowIndex++;
      
              //Inset the data row
              foreach (var contentRow in rows)
              {
                  excelRow = sheet.CreateRow(rowIndex);
      
                  var Properties = rows.First().GetType().GetProperties();
      
                  //Go through each property and inset it into a single cell
                  foreach (var property in Properties)
                  {
                      var cell = excelRow.CreateCell(cellIndex);
                      var value = property.GetValue(contentRow);
      
                      if (value != null)
                      {
                          var dataType = value.GetType();
      
                          //Set the type of excel cell for different data types
                          if (dataType == typeof(int) ||
                              dataType == typeof(double) ||
                              dataType == typeof(decimal) ||
                              dataType == typeof(float) ||
                              dataType == typeof(long))
                          {
                              cell.SetCellType(CellType.NUMERIC);
                              cell.SetCellValue(Convert.ToDouble(value));
                          }
                          if (dataType == typeof(bool))
                          {
                              cell.SetCellType(CellType.BOOLEAN);
                              cell.SetCellValue(Convert.ToDouble(value));
                          }
                          else
                          {
                              cell.SetCellValue(value.ToString());
                          }
                      }
                      cellIndex++;
                  }
      
                  cellIndex = 0;
                  rowIndex++;
              }
      
              //Set the width of the columns
              foreach (string header in headerRow)
              {
                  sheet.AutoSizeColumn(cellIndex);
                  cellIndex++;
              }
      
      
              return workbook.GetDownload(sheetName);
          }
      
          /// <summary>
          /// Converts the NPOI workbook into a byte array for download
          /// </summary>
          /// <param name="file"></param>
          /// <param name="fileName"></param>
          /// <returns></returns>
          public static FileStreamResult GetDownload(this NPOI.HSSF.UserModel.HSSFWorkbook file, string fileName)
          {
              MemoryStream ms = new MemoryStream();
      
              file.Write(ms); //.Save() adds the <xml /> header tag!
              ms.Seek(0, SeekOrigin.Begin);
      
              var r = new FileStreamResult(ms, "application/vnd.ms-excel");
              r.FileDownloadName = String.Format("{0}.xls", fileName.Replace(" ", ""));
      
              return r;
          }
      
          /// <summary>
          /// Get's an attribute from any given property
          /// </summary>
          /// <typeparam name="T"></typeparam>
          /// <param name="instance"></param>
          /// <param name="propertyName"></param>
          /// <returns></returns>
          public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
          {
              var attrType = typeof(T);
              var property = instance.GetType().GetProperty(propertyName);
              return (T)property.GetCustomAttributes(attrType, false).First();
          }
      }
      

      希望对您有所帮助。

      【讨论】:

        【解决方案6】:

        这几天我一直在尝试解决这个问题。最后,我在这里找到了解决方案:http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx

        命名空间:

        using System.IO;
        using System.Data;
        using ClosedXML.Excel;
        

        代码:

        DataTable dt = new DataTable("GridView_Data");
        // Fill your DataTable here...
        
        //Export:
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt);
        
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多