簡體   English   中英

在服務器端生成Excel文件后無法打開

[英]Can't open the excel file after generating it on server side

我已經使用C#編碼生成了excel文件,如下所示

C#編碼:

protected void Page_Load(object sender, EventArgs e)
        {
            var doc = new SpreadsheetDocument(@"D:\JOSEPH\GenerateExcelSheet\OpenXmlPackaging.xlsx");
            Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
            sheet1.Cells[1, 1].Value = "Test";

            sheet1.Cells["A1"].Value = 1;
            sheet1.Cells["C3"].Style = new OpenXmlPackaging.Style {

                Borders = new Borders(BorderStyles.Thick),
                Font = new Font
                {
                    Name = "Consolas",
                    Size = 10,
                    Style = FontStyles.DoubleUnderline | FontStyles.Bold
                },
                NumberFormat = new NumberFormat("#,##0.0;[Red](#,##0.0)"),
                Alignment = new Alignment
                {
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Top,
                    WrapText = true,
                    Rotation = 45
                },
            };
            sheet1.Cells.CreateRange("B10:D5").MergeCells();
            sheet1.AutoFitColumns();
            sheet1.SetColumnWidth(3, 12);


        }

但是當我嘗試打開excel文件時,出現一個消息框,顯示為“ 在此處輸入圖片說明

簡短的答案是,您不應該嘗試像這樣在服務器上創建Excel文件。 使用Excel API來執行此操作存在技術問題和許可問題-您可以在此處閱讀更多信息http://support.microsoft.com/default.aspx/kb/257757

技術問題可以很好地解釋您的文件損壞的原因。

更好的方法是使用不依賴Excel API的庫,我在我的問題/解答中列出了一些作為服務器進程讀取Excel文件的內容 ,可能會對您有所幫助。

將此用於打開的Excel:

     ApplicationClass excel = new ApplicationClass();
            Worksheet sheet1  = Activate(excel);
//insert you'r code

使用它來保存和關閉Excel:

 excel.Visible = true;
object misValue = System.Reflection.Missing.Value;

    sheet1.SaveAs(filename, XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
                    excel.Application.Quit();
                    excel.Quit();

                    Marshal.ReleaseComObject(ws);
                    Marshal.ReleaseComObject(excel);
                    excel = null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM