• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1946
  • Last Modified:

Writing to, saving, and printing excel worksheets via C# and ASP .NET


I have a requirement for a client where I have to allow users to a web form so they can fill out form fields and submit the page. The application is then going to write the form field values to various cells in an Excel spreadsheet and save it under a new name. The newly saved workbook must then have several worksheets converted to pdf documents.

As a proof of concept, I've created a winforms C# project in VS 2005. I am able to open, read, write, and save to an excel worksheet. My issues are with the printing aspect of the process. I had intended to use Adobe's PDF printer driver to export the excel worksheets to pdf files.

The documentation on msdn isn't very descriptive in this regard. See the following code. The only line that will correctly print the excel worksheet to pdf is this one:

objBook.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", true, false, null);

The problem here is that a dialogue pops up requiring a filename to save the file to. The last paramater of the PrintOut method allows for the entry of this filename. The 3rd to last parameter is a boolean that designates whether or not the worksheet/workbook is being printed to a file. The 2nd to last parameter is true for collate and false for not. I'm not even sure what collate does.

It doesn't matter what values I toggle on some of these parameters, I always get an error from the Adboe PDFWriter saying that the file is locked. Sometimes the file is created but is corrupted and has a size of 0 bytes.

I'm open to any and all suggestions so long as they can be done strictly through C# and/or ASP .NET. I really need a solution that can work on the web but if you have a windows only solution I would accept that. I just need to get to the point where I can save to the worksheet and print/export it to a pdf. If you know of 3rd party products that you might have used or heard about that can do this, I would be very interested to know about them.

Basically any and all input is welcome. I have searched extensively on Experts Exchange and found some possibilities but nothing in C# alone and nothing in ASP .net.

The end solution will need to be able to handle the exporting of some fairly complex charts and such; however, don't let this deter you from making suggestions as I'm at an impasse at the moment.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Excel;
 
 
namespace ExcelInteropTesting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        //Declare these two variables globally so you can access them from both
        //Button1 and Button2.
        Excel._Application objApp;
        Excel._Workbook objBook;
 
        private void button3_Click(object sender, EventArgs e)
        {
 
            Excel.Workbooks objBooks;
            Excel.Sheets objSheets;
            Excel._Worksheet objSheet;
            Excel.Range range;
 
            try
            {
                // Instantiate Excel and start a new workbook.
                objApp = new Excel.Application();
                //Don't show dialogs if app is hidden
                objApp.DisplayAlerts = true;
                
                objBooks = objApp.Workbooks;
                objBook = objBooks.Open(@"C:\Development\ExcelInteropTesting\Test.xls",
                        Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value,
                        Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
 
                objSheets = objBook.Worksheets;
                objSheet = (Excel._Worksheet)objSheets.get_Item(1);
                objSheet.Cells[1, "A"] = 8;
                objApp.Visible = true;
                //objApp.ActivePrinter = "Acrobat PDFWriter";
                objApp.UserControl = true;
                objBook.Save();
                //objBook.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", false, false, "C:\\Development\\ExcelInteropTesting\\test6.pdf");
                //objSheet.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", true, false, "test2.pdf");
                //objSheet.PrintOut(1, 1, 1, false, Missing.Value, true, false, "test2.pdf"); 
 
                //Creates corrupt file with 0 bytes of info. Adobe doesn't recognize it or know how to open it.
                //objBook.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", true, true, "C:\\Development\\ExcelInteropTesting\\test6.pdf");
                objSheet.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", true, true, "C:\\Development\\ExcelInteropTesting\\test7.pdf");
 
                //semi working line 
                objBook.PrintOut(1, 1, 1, false, "Acrobat PDFWriter", true, false, null);
               
            }
            catch (Exception theException)
            {
                String errorMessage;
                errorMessage = "Error: ";
                errorMessage = String.Concat(errorMessage, theException.Message);
                errorMessage = String.Concat(errorMessage, " Line: ");
                errorMessage = String.Concat(errorMessage, theException.Source);
 
                MessageBox.Show(errorMessage, "Error");
            }
            finally
            {
                objApp.Workbooks.Close();
                objApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp);
                objSheets = null;
                objSheet = null;
                objBooks = null;
                objBook = null;
                objApp = null;
                GC.Collect();
 
                Environment.Exit(0);
            }
 
 
 
        }
 
 
    }
}

Open in new window

0
baijajusav
Asked:
baijajusav
  • 3
  • 2
1 Solution
 
Éric MoreauSenior .Net ConsultantCommented:
you should not use Excel automation on a web server. consider using http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx which will solve all your problems.
0
 
baijajusavAuthor Commented:

I've looked over the product in detail and that fits the bill perfectly. The price is pretty steep, but beggars can't be choosers. Thanks for the link!

I'll leave this up for another day or so and then assign points.
0
 
baijajusavAuthor Commented:

Okay, it doesn't look like there's any more input to be had here. I'll look into purchasing the Aspose.Cells product. From everything I am seeing, this company seems to be pretty top notch. They've custom modified code for various customers in a pretty big hurry too. In addition to that, it looks like I can open a spreadsheet, modify the cells, save it, export it to pdf, and then prompt the user to download the newly created pdf in under 20 lines of code. That's beyond wicked.

Thanks for the suggestion emoreau.
0
 
baijajusavAuthor Commented:
Suggested product fits the bill perfectly. The price is steep, but there's always a premium on quality.
0
 
Éric MoreauSenior .Net ConsultantCommented:
I have used some of their products and was very satisfied with my experiences and the support they provide.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now