Convert Excel File to PDF Using Excel from .NET

Page update date :
Page creation date :

Operating environment

Visual Studio
  • Visual Studio 2022
.NET
  • .NET 6.0
Windows
  • Windows 11
Excel
  • Microsoft 365

Prerequisites

Windows
  • One of the versions
Excel
  • One of the versions

Steps to convert from an Excel file to a PDF file

This program uses to manipulate Excel from a .NET program Microsoft.Office.Interop.Excel via COM and output the opened Excel file as a PDF. Therefore, Excel must be installed on Windows in order to run. COM is a Windows mechanism, so it doesn't work on Macs.

When you create a project in Visual Studio, it can be anything that runs on the Windows desktop. In this case, we're creating it as a console app.

After you create the project, browse the library for using Excel. The method presented here is built in a way that depends on the version of Excel that is installed for the ease of viewing the program. If you want to run it independently of the version of Excel, modify it according to the method linked below. That's how we build the programs we distribute.

Right-click Dependencies and select Add COM Reference.

If Excel is installed in the development environment, type "" in the search field in the Excel upper right corner, so check Microsoft Excel XX.0 Object Library it and click the "OK" button. The version that is displayed depends on the version of Excel that is installed.

You have an Excel file ready to import. The way it is output to PDF is the same as when you manually output to PDF in Excel, so please check it before you incorporate it as an application.

Enter the following code where you want it to be processed.

// 実行プログラムの場所にある Excel ファイル
var folderPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName) ?? "";
var excelFilePath = Path.Combine(folderPath, "Sample.xlsx");

Microsoft.Office.Interop.Excel.Application? excel = null;
Microsoft.Office.Interop.Excel.Workbooks? books = null;
Microsoft.Office.Interop.Excel.Workbook? book = null;
Microsoft.Office.Interop.Excel.Sheets? sheets = null;
try
{
  // Excel アプリケーション生成
  excel = new Microsoft.Office.Interop.Excel.Application()
  {
    DisplayAlerts = false, // アラート非表示
    Visible = false,       // Excel 非表示
  };

  // ワークブック一覧を参照
  books = excel.Workbooks;

  // Excel ファイルを開く
  book = books.Open(excelFilePath);

  // シート一覧参照
  sheets = book.Worksheets;

  // 全シートを選択
  sheets.Select();

  // Excel のデータを PDF ファイルとして保存
  //   Type     : xlTypePDF=PDF, xlTypeXPS=XPS
  //   Filename : 出力ファイル名
  //   Quality  : xlQualityStandard=標準品質, xlqualityminimum=最小限の品質
  book.ExportAsFixedFormat(
      Type: Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,
      Filename: Path.Combine(folderPath, "Sample.pdf"),
      Quality: Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard);

  Console.WriteLine("PDF 出力に成功しました。");
}
catch (Exception ex)
{
  Console.WriteLine("PDF 出力に失敗しました。");
  Console.WriteLine(ex.ToString());
}
finally
{
  // Excel を終了させる
  if (book != null) book.Close(SaveChanges: false);
  if (excel != null) excel.Quit();

  // 使用した Excel リソースは全て開放する
  if (sheets != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
  if (book != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
  if (books != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
  if (excel != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
}

The point is that Workbook.ExportAsFixedFormat the method already has an export function, so you just need to call it.

Run it to see if the PDF file is output.