Joe Mike
Joe Mike

Reputation: 1170

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

I have generated the excel file using C# coding as shown below

C# Coding:

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


        }

but when i tried to open the excel file, a message box appears as " enter image description here"

Upvotes: 1

Views: 759

Answers (2)

Asieh hojatoleslami
Asieh hojatoleslami

Reputation: 3360

Use this for open Excel:

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

Use this for save and close 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;

Upvotes: 0

Ian
Ian

Reputation: 34489

The short answer is that you shouldn't be trying to create an Excel file on the server like this. There are technical issues and licensing issues of using the Excel API to do this - you can read more here http://support.microsoft.com/default.aspx/kb/257757

The technical problems may well explain why you're file is corrupt.

The better approach would be to use a library that doesn't rely on the Excel API, I listed a few in my question/answer here Reading Excel Files as a Server Process that may help you.

Upvotes: 2

Related Questions