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

Posted on 2009-05-18
Last Modified: 2013-12-17

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()
        //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;
                // 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.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");
                objSheets = null;
                objSheet = null;
                objBooks = null;
                objBook = null;
                objApp = null;

Open in new window

Question by:baijajusav
  • 3
  • 2
LVL 70

Accepted Solution

Éric Moreau earned 500 total points
ID: 24414425
you should not use Excel automation on a web server. consider using which will solve all your problems.

Author Comment

ID: 24423658

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.

Author Comment

ID: 24432532

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.

Author Closing Comment

ID: 31582666
Suggested product fits the bill perfectly. The price is steep, but there's always a premium on quality.
LVL 70

Expert Comment

by:Éric Moreau
ID: 24432712
I have used some of their products and was very satisfied with my experiences and the support they provide.

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question