2017-04-21 4 views
2

Open XML을 사용하여 MVC에서 Excel 문서를 생성 중입니다.OpenXML을 사용하는 MVC 컨트롤러에서 통합 문서를 읽기 전용으로 만들기

public ActionResult ExcelReport() 
{ 
    var custId = 1234; //ToDo get from session when it is set 

    using (MemoryStream mem = new MemoryStream()) 
    { 
    ExcelReportGenerator excel = new ExcelReportGenerator(); 

    excel.CreateExcelDoc(mem); 

    var reportName = string.Format("MyReport_{0}.xlsx", custId); 

    return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, reportName); 
    } 

} 

내 CreateExcelDoc 방법은 다음과 같습니다 :

코드는 다음과 같습니다 예상대로 엑셀 시트를 다운로드하는 create 메소드와

public void CreateExcelDoc(MemoryStream mem) 
{ 
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook); 

    //SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(mem, false); 

    //Code removed for brevity 

    worksheetPart.Worksheet.Save(); 
    spreadsheetDocument.Close(); 

} 

. 그러나, 나는 통합 문서가 읽기 전용 그래서 MEM 스트림을 통과하는 .Open 방법을 시도하고 있었다 만들고 싶어하고 isEditable는 false로 설정하지만 오류 Exception Details: System.IO.FileFormatException: Archive file cannot be size 0.

답변

1

엑셀 읽기 전용을 만드는 더 간단한 방법은 Protect the worksheet (see Step 2 at link)입니다. 나는이 기술을 사용하는 new version of the reference implementation MVC를 추진해 왔습니다

workSheet.Append(new SheetProtection() { Sheet = true, Objects = true, Scenarios = true }); 

:

이 작업을 수행하는 OpenXML을 코드는 한 장에 하나 개의 라인입니다. SheetProtection은 Excel 2007에서 지원되는 것으로 보입니다. Final로 표시는 Excel 2013 이후에만 지원됩니다.

+0

이것이 정확히 내가 필요한 것입니다. - 감사합니다 :) –

1

통화와 컨트롤러를 쳤을 때 나는 YSOD을 얻고있다 SpreadsheetDocument.Open 읽기 전용 파일이 아닙니다. It merely opens the memory stream in read only mode. (isEditable is false) 이것은 나머지 코드에 의해 스트림이 변경되는 것을 잠급니다. 이것은 왜 당신이 그 호출을 추가하기 전에 벌금을 잘 냈는지, 그리고 그 호출을 추가 한 후에 빈 아카이브 예외를 얻는 이유를 설명합니다. 그 목적으로 SpreadsheetDocument.Open을 사용하지 마십시오.

Excel을 읽기 전용 파일로 보내지 않는 것이 좋습니다. 사용자는 모든 운영 체제에서이 파일을 다운로드하여 이름을 바꾸고 파일 권한을 원하는대로 변경할 수 있습니다.

나는 mark your Excel as final이라는 openXML 코드를 추가하는 것이 좋습니다. Microsoft는 Office 문서에이 기능을 추가했습니다. 단순한 파일 권한 대신 사용자가 이후에 파일을 변경하지 못하게하는 것이 공식적으로 금지되어 있기 때문입니다. 이 파일 중 하나가 변경되면 새 파일 이름이 필요합니다.

권장되는 OpenXml 코드는 generate a Custom Property이므로 사용자가 파일을 다운로드하면 최종 편집으로 사용자 편집을 방해 할 수 있습니다. 내가 참조 구현으로 당신을 위해 마지막으로 표시된 빈 Excel 파일을 생성하는 간단한 MVC 응용 프로그램을 작성했습니다

private void GenerateCustomFilePropertiesPart1Content(CustomFilePropertiesPart customFilePropertiesPart1) 
    { 
     Op.Properties properties2 = new Op.Properties(); 
     properties2.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); 

     Op.CustomDocumentProperty customDocumentProperty1 = new Op.CustomDocumentProperty() { FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", PropertyId = 2, Name = "_MarkAsFinal" }; 
     Vt.VTBool vTBool1 = new Vt.VTBool(); 
     vTBool1.Text = "true"; 

     customDocumentProperty1.Append(vTBool1); 

     properties2.Append(customDocumentProperty1); 

     customFilePropertiesPart1.Properties = properties2; 
    } 

: 여기

사용자 정의 속성을 추가 할 방법이다. The code is hosted on GitHub. 당신이 그것을 실행할 때, 가장 오른쪽 메뉴 링크 "Download Excel"을 클릭하십시오. 그러면 Walter 's Workbook이라는 통합 문서 하나가 포함 된 Excel이 다운로드되며 데이터는 제공되지 않습니다. 엑셀은 최종으로 표시됩니다. Custom Property 코드는 OpenXML Productivity Tool을 사용하여 생성되었습니다. 프로젝트에 행운을 빈다.

+0

내 최종 사용자 Excel 2003.Office 2003의 이전 버전을 가질 수 있습니다. 마지막으로 OpenXML에서 작동하지 않으면 다른 라이브러리를 살펴야 할 수도 있습니다. 목적은 이전에 사용했던 것이지만 값 비쌉니다. –