home screen

Search



Number Of Result : 0

Result :


Wednesday, June 9, 2010

Export Excel to Pdf

1. Adding a Reference to the Excel 12.0 Object Library

Begin by adding a reference to the Microsoft Excel 12.0 Object Library to the Visual Studio project.

To add a reference to the Excel 12.0 Object Library
Right-click the project in the Visual Studio Solution Explorer.

Select Add Reference….

Select the COM tab in the Add Reference dialog box.

Scroll down to the Microsoft Excel 12.0 Object Library component and select it.

Click OK to add the reference.



2. Execute

//sourceBookPath = d:\test.xlsx
//targetFilePath = d:\test.pdf
public void ConvertWorkbookToPDF(string sourceBookPath, string targetFilePath)
{
// Make sure the source document exists.
if (!System.IO.File.Exists(sourceBookPath))
throw new Exception("The specified source workbook does not exist.");

// Create an instance of the Excel ApplicationClass object.
ApplicationClass excelApplication = new ApplicationClass();

// Declare a variable to hold the reference to the workbook.
Workbook excelWorkBook = null;

// Declare variables for the Workbooks.Open and ApplicationClass.Quit method parameters.
string paramSourceBookPath = sourceBookPath;
object paramMissing = Type.Missing;

// To save the file in XPS format using the following for the paramExportFilePath
// and paramExportFormat variables:
//
string paramExportFilePath = targetFilePath;

//Export to Pdf
XlFixedFormatType paramExportFormat = XlFixedFormatType.xlTypePDF;

XlFixedFormatQuality paramExportQuality = XlFixedFormatQuality.xlQualityStandard;
bool paramOpenAfterPublish = false;
bool paramIncludeDocProps = true;
bool paramIgnorePrintAreas = true;
object paramFromPage = Type.Missing;
object paramToPage = Type.Missing;

try
{
// Open the source workbook.
excelWorkBook = excelApplication.Workbooks.Open(paramSourceBookPath, paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing, paramMissing, paramMissing);

// Save it in the target format.
if (excelWorkBook != null)
excelWorkBook.ExportAsFixedFormat(paramExportFormat, paramExportFilePath, paramExportQuality, paramIncludeDocProps,
paramIgnorePrintAreas, paramFromPage, paramToPage, paramOpenAfterPublish, paramMissing);
}
catch (Exception ex)
{
// Respond to the error.
Console.WriteLine(ex.Message);
}
finally
{
// Close the workbook object.
if (excelWorkBook != null)
{
excelWorkBook.Close(false, paramMissing, paramMissing);
excelWorkBook = null;
}

// Close the ApplicationClass object.
if (excelApplication != null)
{
excelApplication.Quit();
excelApplication = null;
}

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}


- Configure to run Excel in Window Server: http://blog.crowe.co.nz/archive/2006/03/02/589.aspx

No comments: