LoginSignup
3
5

More than 3 years have passed since last update.

C#エクセルの印刷方法

Posted at

エクセルの印刷方法がエクセルで行われるなら、簡単だそうですが、プログラマー達はC#で作業したいと思っているなら、どうするかしら?今日はSpire.XLSというライブラリを紹介することにします。そして、「通常使うプリンターで印刷」「指定するプリンターで印刷」「サイレント印刷」という三つの方法でエクセルを印刷する方法を見せてあげましょう。

下準備

1.E-iceblueの公式サイトからFree Spire.XLS無料版をダウンロードしてください。

f:id:lendoris:20201118110355p:plain

2.Visual Studioを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.XLS.dllを参照に追加してください。

(Net 4.0を例としたら、デフォルトパスは“Bin→NET4.0→XLS.dll”というようです。)

f:id:lendoris:20201118110552p:plain

通常使うプリンターで印刷

ただworkbook.PrintDocument.Print()メソードを使ってOKです。

using Spire.Xls;

namespace ConsoleApplication26

{

class Program

{

static void Main(string[] args)

{



Workbook workbook = new Workbook();

workbook.LoadFromFile("Sample.xlsx");

workbook.PrintDocument.Print();

}

}

}

指定するプリンターで印刷

 

f:id:lendoris:20201118110649p:plain
ページ設定で印刷の向き・用紙サイズ・印刷範囲などを設定することができます。

 サンプルコード 

//印刷範囲を設定します。

sheet.PageSetup.PrintArea = "B2:F8";



//タイトルを印刷します。

sheet.PageSetup.PrintTitleColumns = "$A:$B";

sheet.PageSetup.PrintTitleRows = "$1:$2";



//印刷の順を設定します。

sheet.PageSetup.Order = OrderType.DownThenOver;

sheet.PageSetup.Order = OrderType.OverThenDown;



// PrintDialogを設定します。

PrintDialog dialog = new PrintDialog();

dialog.AllowPrintToFile = true;

dialog.AllowCurrentPage = true;

dialog.AllowSomePages = true;



//片面印刷します。

dialog.PrinterSettings.Duplex = Duplex.Simplex;



//印刷範囲を設定します。

dialog.PrinterSettings.FromPage = 0;

dialog.PrinterSettings.ToPage = 8;

dialog.PrinterSettings.PrintRange = PrintRange.SomePages;



//部数を設定します。

dialog.PrinterSettings.Copies = 5;



//プリンターの名前を設定します。

dialog.PrinterSettings.PrinterName = "HP LasterJet P1007";



//印刷します。

workbook.PrintDialog = dialog;

PrintDocument pd = workbook.PrintDocument;

if

(dialog.ShowDialog() == DialogResult.OK)

{

pd.Print();

}

 

サイレント印刷

using Spire.Xls;

using System.Drawing.Printing;

namespace ConsoleApplication26

{

class Program

{

static void Main(string[] args)

{



//Excelをロードします。

Workbook workbook = new Workbook();

workbook.LoadFromFile("Sample.xlsx");



//サイレント印刷します。

workbook.PrintDocument.PrintController = new StandardPrintController();

workbook.PrintDocument.Print();

}

}

}

 

 

 

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5