La generazione di fogli di calcolo Excel produce & # 8220; formato file diverso dall'errore di estensione & # 8221; all'apertura in Excel 2007

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

  •  19-08-2019
  •  | 
  •  

Domanda

Il foglio di calcolo viene ancora visualizzato, ma con il messaggio di avviso. Il problema sembra verificarsi perché Excel 2007 è più esigente riguardo ai formati corrispondenti alle loro estensioni rispetto alle versioni precedenti di Excel.

Il problema è stato inizialmente rilevato da un programma ASP.Net e produce nell'errore Excel "Il file che si sta tentando di aprire", Spreadsheet.aspx-18.xls ", è in un formato diverso da quello specificato da estensione del file. Verifica ... " ;. Tuttavia, quando apro il file viene visualizzato correttamente. Sto usando Excel 2007. Firefox identifica il file come un foglio di lavoro Excel 97-2003.

Ecco una pagina ASP.NET che genera il problema:

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

Il codice dietro il file è simile a:

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

È stato utile?

Soluzione

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

Questo è un collegamento che descrive sostanzialmente che MS è a conoscenza del problema descritto e che non può essere eliminato dal codice ASP.NET. Deve essere soppresso / riparato nel registro del client.

Altri suggerimenti

Se sei come me e stai generando il foglio Excel come documento XML del 2003, puoi rimuovere gli avvisi nel modo seguente:

Aggiunto all'output XML:

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

Aggiunto alla pagina di download:

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

Ora Excel 2007 non visualizzerà un avviso che il contenuto e l'estensione del file non corrispondono.

Ho visto questa domanda più volte. Ho incontrato la stessa difficoltà oggi, quindi ho risolto il problema utilizzando 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();
    }
}

Spero che lo trovi utile.

Stavo cercando di risolvere questo problema da alcuni giorni. Infine, ho trovato la soluzione qui: http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView -export-to-Excel-The-file-si-sta-tentando-to-open-è-in-a-diverso-formato-che-specificato-by-the-file-extension.aspx

namespace:

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

Codice:

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

Sono più affezionato all'utilizzo di una griglia e alla modifica del tipo di risposta che devo ancora avere un problema con quella metodologia. Non ho usato file delimitati da tabulazioni diritte. Una possibilità è che potrebbe essere necessario \ n \ r \ n. Solo un colpo cieco.

Usa

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

E specifica l'estensione come xlsx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top