xin9le.net

Microsoft の製品/技術が大好きな Microsoft MVP な管理人の技術ブログです。

サクッと簡単!Excel → PDF 変換

会社で今日こんなお願いをされました。

このフォルダ以下にある全部の Excel ファイルを PDF にしてほしい!ファイル数メッチャあるからチマチマやってられーん!Help !!

ということでサクッとツールを作ってあげたわけですが、案外便利なのではないかと思ったので載せておきます。

f:id:xin9le:20160721220738p:plain

Excel → PDF 変換

Office PIA (相互運用アセンブリ) を使って変換するためのエッセンスは以下のような感じです。Workbook.ExportAsFixedFormat メソッドを使いましょうPDF だけでなく XPS 形式での出力も可能です。

var sourcePath = @"C:\Temp\sample.xlsx";
var targetPath = sourcePath.Replace(".xlsx", ".pdf");
var format = XlFixedFormatType.xlTypePDF;
var quality = XlFixedFormatQuality.xlQualityStandard;

var app = new Application();
var workbook = app.Workbooks.Open(sourcePath);  //---ブックを開いて
workbook.ExportAsFixedFormat(format , targetPath, quality);  //--- PDF形式で出力
app.Quit();

ソースコード

とりあえずでワンポイントで動けばいい系なので超絶雑ぃですが、全体像でもこれだけです。app.config に対象フォルダの指定を外出ししてあるので汎用的に利用できます。

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Office.Interop.Excel;

namespace Excel2Pdf
{
    class Program
    {
        static void Main()
        {
            var rootPath = ConfigurationManager.AppSettings["SourceFolderPath"];
            var files = Directory.GetFiles(rootPath, "*.xlsx", SearchOption.AllDirectories);

            //--- 件数
            Console.WriteLine($"対象フォルダ : {rootPath}");
            Console.WriteLine($"ファイル数 : {files.Length}");

            //--- 開始確認
            Console.WriteLine("Please press any key to start.");
            Console.ReadLine();

            //--- 変換
            for (int i = 0; i < files.Length; i++)
            {
                var path = files[i];
                Console.WriteLine($"{i + 1}/{files.Length} : {path.Replace(rootPath, string.Empty)}");
                Convert(path);
                GC.Collect();
            }

            //--- おまじない的に3秒ほど待ってみる
            Thread.Sleep(3000);

            //--- Excel.exe が死ななかったら困るので、念のためプロセスを強制的に殺す処理を入れておく
            var excels = Process.GetProcessesByName("EXCEL");
            foreach (var x in excels)
                x.Kill();
        }

        static void Convert(string sourcePath)
        {
            Application app = null;
            Workbook workbook = null;
            try
            {
                //--- Excelファイルを開く
                app = new Application();
                workbook = app.Workbooks.Open(sourcePath);

                //--- PDFとして保存
                var targetPath = sourcePath.Replace(".xlsx", ".pdf");
                workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath, XlFixedFormatQuality.xlQualityStandard);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー : {ex.Message}");
            }
            finally
            {
                if (workbook != null)
                {
                    Marshal.ReleaseComObject(workbook);
                    workbook = null;
                }

                //--- Excelを終了
                app.Quit();
                Marshal.ReleaseComObject(app);
                app = null;
            }
        }
    }
}

こんなので人助けになって喜ばれるんだから、プログラミングはできて損しないですね!