2009-03-16 7 views
29

Die Tabelle wird weiterhin angezeigt, aber mit der Warnmeldung. Das Problem scheint aufzutreten, da Excel 2007 bei Formaten, die mit ihren Erweiterungen übereinstimmen, wählerischer ist als frühere Versionen von Excel.Excel Tabellenkalkulation Generation führt zu "anderen Dateiformat als Erweiterung Fehler" beim Öffnen in Excel 2007

Das Problem wurde ursprünglich von einem ASP.Net-Programm entdeckt und erzeugt im Excel-Fehler "Die Datei, die Sie versuchen zu öffnen", Spreadsheet.aspx-18.xls ', ist in einem anderen Format als von der Datei angegeben Erweiterung. Verify ... ". Wenn ich die Datei öffne, wird sie jedoch einwandfrei angezeigt. Ich verwende Excel 2007. Firefox identifiziert die Datei als Excel 97-2003-Arbeitsblatt.

Hier ist eine ASP.NET-Seite, die das generiert Problem:

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

Der Code hinter Datei wie folgt aussieht:

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

+0

Bitte beachten Sie http://support.microsoft.com/kb/948615 –

Antwort

28

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

Das ist ein Link im Grunde beschreibt, dass MS kennt das Problem, das Sie beschreiben, und dass es nicht aus dem ASP.NET-Code unterdrückt werden kann. Es muss in der Client-Registrierung unterdrückt werden.

+0

Ich habe dies festgestellt, das ist das Problem. – brendan

+3

Der Artikel bietet auch einen anderen Fix, der die Registrierung nicht ändert. Ich habe die Zeile hinzugefügt: Response.AddHeader ("Content-Disposition", "Anhang; Dateiname = Spreadsheet.csv"); und dann eine kommagetrennte Datei generiert. Ich hätte Registerkarten mit einer TXT-Datei verwenden können. –

+2

Weiter zu Jeff Bloom, siehe meine Antwort unten, wenn Sie ausgegeben werden, ist Excel als XML –

0

Ich benutze lieber ein Grid und ändere den Antworttyp Ich habe noch kein Problem mit dieser Methode. Ich habe keine durch Tabulatoren getrennten Dateien verwendet. Eine Möglichkeit ist, dass \ n möglicherweise \ r \ n sein muss. Nur ein Blindschuss.

-2

Verwenden

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

und gibt Erweiterung als xlsx

18

Wenn Sie wie ich sind und die Excel-Tabelle als 2003 XML-Dokument zu erzeugen, können Sie die Warnungen entfernen, indem Sie die folgenden Schritte aus:

hinzugefügt, um die XML-Ausgabe:

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

hinzugefügt, um die Download-Seite:

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

Jetzt Excel 2007 wird ein nicht angezeigt warnen dass Dateiinhalt und Dateierweiterung nicht übereinstimmen.

+3

Das bedeutet, dass die Datei nicht automatisch mit Excel geöffnet wird ... – gb2d

+2

@BombDefused Sie sollte sich automatisch mit Excel öffnen. Wenn Sie eine Version von Excel> 2003 haben, erleichtert die Zeile '' Dies. Wenn es nicht funktioniert, kann dies an Dateizuordnungen oder einer Excel-Einstellung liegen. –

2

Ich habe diese Frage oft gestellt. Ich lief in die gleiche Schwierigkeit heute so fixiert ich das Problem mit 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(); 
    } 
} 

Hoffe Sie dies hilfreich.

1

Ich habe versucht, dieses Problem während einiger Tage zu beheben.Schließlich habe ich hier die Lösung gefunden: 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

Namespaces:

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