web-dev-qa-db-fra.com

La génération de feuille de calcul Excel entraîne "un format de fichier différent de celui lié à une extension" lors de l'ouverture dans Excel 2007

La feuille de calcul s'affiche toujours, mais avec le message d'avertissement. Le problème semble se produire car Excel 2007 est plus pointilleux que les versions antérieures d'Excel en ce qui concerne les formats correspondant à leurs extensions.

Le problème a été initialement découvert par un programme ASP.Net et génère dans l'erreur Excel "Le fichier que vous essayez d'ouvrir," Spreadsheet.aspx-18.xls ', est dans un format différent de celui spécifié par l'extension de fichier. Verify ... ". Cependant, lorsque j'ouvre le fichier, il s'affiche correctement. J'utilise Excel 2007. Firefox identifie le fichier en tant que feuille de calcul Excel 97-2003. 

Voici une page ASP.NET qui génère le problème:

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

Le code derrière le fichier ressemble à:

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

30
Jeff Bloom

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

Il s’agit en fait d’un lien décrivant le fait que MS connaît le problème que vous décrivez et qu’il ne peut pas être supprimé à partir du code ASP.NET. Il doit être supprimé/fixé sur le registre du client.

29
Eric H

Si vous êtes comme moi et que vous générez la feuille Excel en tant que document XML 2003, vous pouvez supprimer les avertissements en procédant comme suit:

Ajouté à la sortie XML:

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

Ajouté à la page de téléchargement:

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

Désormais, Excel 2007 n’affiche pas d’avertissement indiquant que le contenu du fichier et son extension ne correspondent pas.

18
Gavin Miller

J'ai vu cette question posée à plusieurs reprises. J'ai rencontré le même problème aujourd'hui, j'ai donc résolu le problème avec 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();
    }
}

J'espère que ceci vous aidera.

2
AnonUser

J'essayais de résoudre ce problème pendant quelques jours. Enfin, j'ai trouvé la solution ici: http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open- est-dans-un-format-autre-que-spécifié-par-le-fichier-extension.aspx

Espaces de noms:

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

Code:

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

Je suis plus habitué à utiliser une grille et à changer le type de réponse. Je n'ai toujours pas eu de problème avec cette méthodologie. Je n'ai pas utilisé de fichiers séparés par des tabulations droites. Une possibilité est que le\n doive être\r\n. Juste un coup aveugle.

0
Gregory A Beamer