2009-03-16 8 views
29

Bảng tính vẫn hiển thị nhưng có thông báo cảnh báo. Vấn đề dường như xảy ra bởi vì Excel 2007 là cầu kỳ hơn về các định dạng phù hợp với các phần mở rộng của họ so với các phiên bản trước của Excel.Kết quả tạo bảng tính Excel ở định dạng tệp khác với lỗi tiện ích mở rộng "khi mở trong excel 2007

Vấn đề ban đầu được phát hiện bởi một chương trình ASP.Net và tạo ra lỗi Excel "Tệp bạn đang cố gắng mở", Spreadsheet.aspx-18.xls ', có định dạng khác với tệp được chỉ định sự mở rộng. Xác minh ... ". Tuy nhiên, khi tôi mở tệp nó hiển thị tốt. Tôi đang sử dụng Excel 2007. Firefox xác định tệp dưới dạng trang tính Excel 97-2003.

Đây là trang ASP.NET tạo vấn đề:

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

mã đằng sau tập tin trông giống như:

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

Vui lòng tham khảo http://support.microsoft.com/kb/948615 –

Trả lời

28

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

Đó là một liên kết cơ bản mô tả rằng MS biết về các vấn đề mô tả của bạn và rằng nó không thể bị đàn áp từ bên trong mã ASP.NET. Nó phải được đàn áp/cố định trên registry của khách hàng.

+0

Tôi đã gặp phải điều này, đây là vấn đề. – brendan

+3

Bài viết cũng cung cấp một bản sửa lỗi khác, không liên quan đến việc sửa đổi sổ đăng ký. Tôi đã thêm dòng: Response.AddHeader ("Content-Disposition", "Attachment; Filename = Spreadsheet.csv"); và sau đó tạo tệp được phân tách bằng dấu phẩy. Tôi có thể đã sử dụng các tab có tệp .txt. –

+2

Hơn nữa để Jeff Bloom, xem câu trả lời của tôi dưới đây nếu bạn đang xuất sắc là excel như xml –

0

Tôi aam thích sử dụng lưới và thay đổi kiểu phản hồi mà tôi chưa có vấn đề với phương pháp đó. Tôi đã không sử dụng các tệp phân cách tab thẳng. Một khả năng là \ n có thể phải là \ r \ n. Chỉ là một cú mù.

-2

Sử dụng

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

Và xác định phần mở rộng như xlsx

18

Nếu bạn đang như tôi và tạo ra các tấm Excel như tài liệu XML năm 2003, bạn có thể loại bỏ các cảnh báo bằng cách làm như sau:

Đã thêm vào đầu ra XML:

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

Đã thêm vào trang tải xuống:

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

Bây giờ Excel 2007 sẽ không hiển thị cảnh báo mà nội dung tệp và đuôi tệp không khớp.

+3

Điều này có nghĩa là tệp không tự động mở bằng excel mặc dù ... – gb2d

+2

@BombDefused Nó sẽ tự động mở bằng excel. Nếu bạn đã có một phiên bản của excel> 2003 dòng ' 'Sẽ tạo điều kiện cho điều đó. Nếu nó không hoạt động, nó có thể là do các liên kết tập tin hoặc thiết lập excel. –

2

Tôi đã thấy câu hỏi này được hỏi nhiều lần. Tôi chạy vào khó khăn tương tự hiện nay vì vậy tôi cố định vấn đề sử dụng 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(); 
    } 
} 

Hy vọng bạn thấy hữu ích này.

1

Tôi đã cố gắng giải quyết vấn đề này trong một số ngày.Cuối cùng, tôi đã tìm thấy các giải pháp ở đây: 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(); 
     } 
    }