Existing answers all look good, I note that the target site does not want to have to install Office 2007, and so this answer will not work in that instance. In my case, I wanted the answer to this question where Office 2007 was already installed.
Hopefully the C# code below is useful to the next person who comes looking.
Office 2007
Clearly you will need the Office 2007 PIAs installed on your development machine and on the target machine for this solution to work.
Create a reference in your project to Microsoft.Office.Interop.Excel. The Office 2007 Version I am coding to below is Version 12.0.0.0. Hopefully higher versions will continue to work, but lower versions are unlikely to.
The Code
using System;
using System.IO;
using msExcel = Microsoft.Office.Interop.Excel;
namespace scpm {
public class ExcelToPdfConverter {
private static object missing = System.Reflection.Missing.Value;
public static void ConvertExcelToPdf(string excelFileIn, string pdfFileOut) {
msExcel.Application excel = new msExcel.Application();
try {
excel.Visible = false;
excel.ScreenUpdating = false;
excel.DisplayAlerts = false;
FileInfo excelFile = new FileInfo(excelFileIn);
string filename = excelFile.FullName;
msExcel.Workbook wbk = excel.Workbooks.Open(filename, missing,
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing);
wbk.Activate();
object outputFileName = pdfFileOut;
msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;
// Save document into PDF Format
wbk.ExportAsFixedFormat(fileFormat, outputFileName,
missing, missing, missing,
missing, missing, missing,
missing);
object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges;
((msExcel._Workbook)wbk).Close(saveChanges, missing, missing);
wbk = null;
}
finally {
((msExcel._Application)excel).Quit();
excel = null;
}
}
}
}
References
MSDN article with similar code: http://msdn.microsoft.com/en-us/library/bb407651.aspx and the official docs on ExportAsFixedFormat: http://msdn.microsoft.com/en-us/library/bb238907.aspx
A Caveat
I have one problem with this. If I supply a temporary filename, e.g. from using System.IO.Path.GetTempFileName();
- to give me c:\Users\scpm\AppData\Local\Temp\tmp5166.tmp, excel will actually save it as c:\Users\scpm\AppData\Local\Temp\tmp5166.tmp.pdf which is a bit of a pain.
If anyone has a resolution to this issue, please post in the comments and I will update the code.
If you keep the extension in the pdfFileOut as .pdf then this code works reasonably well.