31

电子表格仍会显示,但会显示警告消息。出现这个问题的原因似乎是 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"); 

    } 

}

4

6 回答 6

29

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

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

于 2009-03-16T22:40:43.483 回答
18

如果您像我一样将 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 将不会显示文件内容和文件扩展名不匹配的警告。

于 2009-07-21T14:56:31.217 回答
2

我看到这个问题被问了很多次。我今天遇到了同样的困难,所以我使用 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();
    }
}

希望你觉得这很有帮助。

于 2013-04-28T02:39:03.670 回答
1

我试图在几天内解决这个问题。最后,我在这里找到了解决方案:http ://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-与文件扩展名指定的格式不同的格式.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();
        }
    }
于 2015-05-12T08:05:30.240 回答
0

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

于 2009-03-16T22:30:22.870 回答
-2

采用

内容类型=应用程序/vnd.openxmlformats-officedocument.spreadsheetml.sheet

并将扩展名指定为 xlsx

于 2009-03-16T22:39:56.247 回答