La generación de hojas de cálculo de Excel da como resultado & # 8220; un formato de archivo diferente al error de extensión & # 8221; Al abrir en Excel 2007

StackOverflow https://stackoverflow.com/questions/652377

  •  19-08-2019
  •  | 
  •  

Pregunta

La hoja de cálculo todavía se muestra, pero con el mensaje de advertencia. El problema parece ocurrir porque Excel 2007 es más exigente con los formatos que coinciden con sus extensiones que las versiones anteriores de Excel.

El problema fue descubierto inicialmente por un programa ASP.Net y produce en el error de Excel "El archivo que está intentando abrir", Spreadsheet.aspx-18.xls ', está en un formato diferente al especificado por el extensión de archivo. Verificar ... ''. Sin embargo, cuando abro el archivo se muestra muy bien. Estoy usando Excel 2007. Firefox identifica el archivo como una hoja de cálculo Excel 97-2003.

Aquí hay una página ASP.NET que genera el problema:

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

El código detrás del archivo se ve así:

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

¿Fue útil?

Solución

http://blogs.msdn.com/vsofficedeveloper/ páginas / Excel-2007-Extension-Warning.aspx

Ese es un enlace que básicamente describe que MS conoce el problema que describe y que no se puede suprimir desde el código ASP.NET. Debe suprimirse / repararse en el registro del cliente.

Otros consejos

Si es como yo y genera la Hoja de Excel como documento XML 2003, puede eliminar las advertencias haciendo lo siguiente:

Agregado a la salida XML:

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

Agregado a la página de descarga:

// 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");

Ahora Excel 2007 no mostrará una advertencia de que el contenido y la extensión del archivo no coinciden.

He visto esta pregunta muchas veces. Me encontré con la misma dificultad hoy, así que solucioné el problema usando 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();
    }
}

Espero que encuentres esto útil.

Intenté resolver este problema durante algunos días. Finalmente, he encontrado la solución aquí: http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView -Exportar a Excel-El-archivo-que-está-intentando-abrir-está-en-un-formato-diferente-que-especificado-por-la-extensión-archivo.aspx

Espacios de nombres :

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

Código :

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();
        }
    }

Soy más aficionado a usar una cuadrícula y cambiar el tipo de respuesta. Todavía no tengo problemas con esa metodología. No he usado archivos delimitados por tabulaciones rectas. Una posibilidad es que el \ n podría ser \ r \ n. Solo un tiro a ciegas.

Uso

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

Y especifique la extensión como xlsx

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top