2014-09-09 15 views
7

Tôi đang tạo tệp Excel bằng thư viện EPPlus. Khi tôi tạo tệp và mở tệp, thông báo bật lên sau hiển thị:Hộp thoại báo lỗi hiển thị khi mở tệp excel được tạo bằng EPPlus

Chúng tôi đã phát hiện sự cố với một số nội dung trong 'ExcelDemo.xlsx'. Bạn có muốn chúng tôi cố gắng phục hồi càng nhiều càng tốt? Nếu bạn tin tưởng là nguồn gốc của cuốn sách này, Nhấn Yes

Tôi đang sử dụng đoạn mã sau

using (ExcelPackage pck = new ExcelPackage()) 
{ 
    //Create the worksheet 
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo"); 

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 
    ws.Cells[1, 2].Value = "Excel Download"; 

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
    Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx"); 
    Response.BinaryWrite(pck.GetAsByteArray()); 
} 

Có vấn đề trong mã của tôi hay đây là một vấn đề Excel?

+0

Tôi đã tìm thấy [diễn đàn này] (https://social.technet.microsoft.com/Forums/office/en-US/f217048b-aa7c-4b6e-a346-59e0445543f6/we-found-a-problem-with- một số nội dung-trong-filenamexlsxdo-bạn-muốn-chúng tôi-to-try-to-phục hồi-as-nhiều-như? diễn đàn = excel) cho thấy bạn chỉ có thể sử dụng tài sản 'Cell.Value' cho các số gây ra vấn đề bạn thấy. – chancea

Trả lời

21

Khi bắt đầu, bạn cần phải thêm vào một:

Response.Clear(); 

Sau đó, ở cuối thêm một

Response.End(); 
+1

Tôi đã gặp sự cố tương tự và điều này đã khắc phục sự cố, thật dễ dàng! Cảm ơn đã giúp đỡ! –

+0

tuyệt vời. Dễ dàng và hoạt động –

2

tôi sẽ chia sẻ giải pháp của tôi. Tôi đang sử dụng một tập tin mẫu excel và sau đó tạo excel mới từ nó.

Nhận cùng lỗi. Mã của tôi là

using (Stream newFileStream = File.Open(this.tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) 
using (Stream originalFile = File.Open(this.initialFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
using (ExcelPackage excelPackage = new ExcelPackage(newFile, template)) 
{ 
     // ... Do work here 
} 

tôi đã phải thay đổi mã để:

FileInfo intialInfo = new FileInfo(this.initialFilePath); 
FileInfo tempFileInfo = new FileInfo(this.tempFilePath); 
using (ExcelPackage excelPackage = new ExcelPackage(tempFileInfo, intialInfo)) 
{ 
    //... Do work here 
} 

Ngoài ra tôi đang sử dụng ASP MVC và phản ứng là:

byte[] result = exporter.GetBytesFromGeneratedExcel(); 
return this.File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Test.xlsx"); 
0

Trong trường hợp của tôi vấn đề là trong việc kêu gọi

package.Save(); 

và sử dụng

Response.BinaryWrite(package.GetAsByteArray()); 

cùng một lúc.

hoạt động Khi bạn gọi package.GetAsByteArray() nó perfoms sau nội bộ:

this.Workbook.Save(); 
this._package.Close(); 
this._package.Save(this._stream); 

Vì vậy, gọi package.Save hai lần dẫn đến lỗi này khi mở trong Excel.

Các vấn đề liên quan