C#で、PDF出力エクセル入出力
C#でPDF出力
C#で、PDFを出力しようと思ったら、何らかのライブラリを使うほうが楽。
というわけで、C#をPDFで出力するための方法を備忘録として記述する。
iTextSharp
iTextSharpは、javaでいうところのiTextをC#に実装しなおしたものらしい。
使い方は簡単で、
VSSの[ツール]ー[NuGetパッケージマネージャー]ー[パッケージマネージャーコンソール]を選択すると、VSSにパッケージマネージャーコンソールという画面が現れる。
このパッケージマネージャーコンソールで、
PM> Install-Package iTextSharp -Version 5.5.12
[PM>はプロンプトで入力する必要はない]
と書くとばらばらと文字が出てきて
最終的に
'iTextSharp 5.5.12' が iTextSharpTest に正常にインストールされました
と、画面に出てきたらOK.
あとは、usingに、
using System.IO; // for iTextSharp
using iTextSharp.text.pdf; // for iTextSharp
using iTextSharp.text; // for iTextSharp
を追加して、
//A4サイズを横向きで
Document pdfDocument = new Document(PageSize.A4.Rotate(), 0, 0, 0, 0);
//出力先のファイル名
string makePdfFilePath = @"c:\PDF\test.pdf";
//FileStream fileStream = new FileStream(makePdfFilePath, FileMode.Create);
FileStream fileStream = new FileStream(makePdfFilePath, FileMode.Append);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, fileStream);
//PDFドキュメントを開く
pdfDocument.Open();
//フォント名
string fontName = "MS ゴシック";
//フォントサイズ
float fontSize = 10.0f;
//フォントスタイル。 複合するときは、&で。
int fontStyle = iTextSharp.text.Font.BOLD;// &iTextSharp.text.Font.ITALIC;
//フォントカラー
BaseColor baseColor = BaseColor.BLACK;
//Fontフォルダを指定
FontFactory.RegisterDirectory(Environment.SystemDirectory.Replace("system32", "fonts"));
//フォントの設定
iTextSharp.text.Font font =
FontFactory.GetFont(fontName,
BaseFont.IDENTITY_H, //横書き
BaseFont.NOT_EMBEDDED, //フォントを組み込まない
fontSize,
fontStyle,
baseColor);
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
ColumnText columnText = new ColumnText(pdfContentByte);
//SetSimpleColumnで出力
columnText.SetSimpleColumn(
new Phrase("…まみむめも☆彡", font)
, 150 // X1位置
, 100 // Y1位置
, 160 // X2位置
, 140 // Y2位置
, fontSize
, Element.ALIGN_LEFT //ちなみに、SetSimpleColumnでは、ALIGN_MIDDLE(縦方向の中寄せ)は使えない
);
//テキスト描画
columnText.Go();
//PDFドキュメントを閉じる
pdfDocument.Close();
こんな感じで、適当にbutton1_Clickとかに入れたらOK.
参考サイト
C# iTextSharpで日本語のPDFファイルを出力 | テクニカルノート
C#でExcel入出力
これも、パッケージマネージャコンソールで、
PM> Install-Package NPOI -Version 2.3.0
と入力すればOK.
'NPOI 2.3.0' が iTextSharpTest に正常にインストールされました
と出ればOK.
xlsxにもxlsにも対応している.
ーーー読み込みーーー
//NPOIで、表示文字列を取得する.
private void button3_Click(object sender, EventArgs e)
{
string filePath = @"C:\pdf\sample2.xlsx";
IWorkbook wb;
// FileShare.ReadWrite の指定は、他プロセスがオープン中でも
// エラーとならないようにするため
using (FileStream infile = new FileStream(filePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
// エクセルファイルを開いて、ワークブック情報を全て取得
wb = WorkbookFactory.Create(infile, ImportOption.All);
}
// シート名を指定して、シート情報を取得
ISheet sheet = wb.GetSheet("newSheet");
// A1形式の文字列でセルを取得する。
// 豆知識:文字列の前後にスペースがあってはいけない
CellReference reference = new CellReference("B1"); // A1形式
// 行を取得
IRow row = sheet.GetRow(reference.Row);
if (row != null)
{
// セルを取得
ICell cell = row.GetCell(reference.Col);
//MessageBox.Show(cell.ToString());
}
MessageBox.Show(this.getCell(sheet, 1, 2));
}
public String getCell(ISheet sheet, int iRow, int iCol)
{
String szRet = "";
CellReference cRef = new CellReference( iRow, iCol );
CellReference cRef2 = new CellReference ( cRef.FormatAsString() );
IRow row = sheet.GetRow(cRef2.Row);
ICell cell;
if (row != null)
{
// セルを取得
cell = row.GetCell(cRef2.Col);
//MessageBox.Show(cell.ToString());
szRet = cell.ToString();
}
return szRet;
}
こんな感じで、読み込む.
ーーー書き込みーーー
private void button2_Click(object sender, EventArgs e)
{
try
{
//ブック読み込み
var book = WorkbookFactory.Create(@"C:\pdf\sample.xlsx");
//シート名からシート取得
var sheet = book.GetSheet("newSheet");
//セルに設定
WriteCell(sheet, 0, 0, "0-0");
WriteCell(sheet, 1, 1, "1-1");
WriteCell(sheet, 0, 3, 100);
WriteCell(sheet, 0, 4, DateTime.Today);
//日付表示するために書式変更
var style = book.CreateCellStyle();
style.DataFormat = book.CreateDataFormat().GetFormat("yyyy/mm/dd");
WriteStyle(sheet, 0, 4, style);
//ブックを保存
using (var fs = new FileStream(@"C:\pdf\sample2.xlsx", FileMode.Create))
{
book.Write(fs);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
//ブック作成
static IWorkbook CreateNewBook(string filePath)
{
IWorkbook book;
var extension = Path.GetExtension(filePath);
// HSSF => Microsoft Excel(xls形式)(excel 97-2003)
// XSSF => Office Open XML Workbook形式(xlsx形式)(excel 2007以降)
if (extension == ".xls")
{
book = new HSSFWorkbook();
}
else if (extension == ".xlsx")
{
book = new XSSFWorkbook();
}
else
{
throw new ApplicationException("CreateNewBook: invalid extension");
}
return book;
}
//セル設定(文字列用)
public static void WriteCell(ISheet sheet, int columnIndex, int rowIndex, string value)
{
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
cell.SetCellValue(value);
}
//セル設定(数値用)
public static void WriteCell(ISheet sheet, int columnIndex, int rowIndex, double value)
{
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
cell.SetCellValue(value);
}
//セル設定(日付用)
public static void WriteCell(ISheet sheet, int columnIndex, int rowIndex, DateTime value)
{
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
cell.SetCellValue(value);
}
//書式変更
public static void WriteStyle(ISheet sheet, int columnIndex, int rowIndex, ICellStyle style)
{
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
cell.CellStyle = style;
}
こんな感じ。
参考サイト
[ NPOI C# ] A1形式の文字列でセル情報を取得する ( CellReference ) – 行け!偏差値40プログラマー
POI CellReferenceメモ(Hishidama's Apache POI CellReference Memo)
A1形式に対応している!と書いているが数値でしたいので、関数化した。
ただ、A1形式も使うことがあるかもしれないので、オーバーロードさせてもよいかも。