メインコンテンツへスキップ
  1. 開発室/
  2. OpenXML SDK/

セルの書式設定 - フォントの操作

openxmlsdk - この記事は連載の一部です
パート 14: この記事

以前の記事「セルの書式設定 - その2」を踏まえて、セルのフォントを操作するコードを紹介します。

今回処理対象とするシートはA列のいくつかのセルに文字が入力されています。

処理対象のシート

ファイル名は「C:\Users\Public\Documents\openxmlsdk14.xlsx」としています。 このシートのA1, A2のフォントを変更するコードを以下に示します。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace OpenXMLSDK_Sample7 {
    class Program {
        static void Main(string[] args) {
            const string FILE = @"C:\Users\Public\Documents\openxmlsdk14.xlsx";
            const string SHEET_NAME = "Sheet1";

            using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(FILE, true)) {
                WorkbookPart bookPart = excelDoc.WorkbookPart;

                int sheet_index = GetWorksheetIndex(bookPart, SHEET_NAME);
                WorksheetPart sheet_part = GetWorksheetPart(bookPart, sheet_index);

                //A1
                Cell cell = GetCell(sheet_part, "A1");
                
                Font font = new Font() {
                    Color = new Color() { Rgb = new HexBinaryValue("FF00FF00") },
                    Bold = new Bold() { Val = new BooleanValue(true) }
                };

                SetFont(bookPart, cell, SHEET_NAME, font);
                
                //A2
                cell = GetCell(sheet_part, "A2");
                font = new Font() {
                    Color = new Color() { Indexed = new UInt32Value((uint)4) },
                    FontName = new FontName() { Val = "Times New Roman" },
                    FontSize = new FontSize() {  Val = new DoubleValue(14.0) },
                    Strike = new Strike() { Val = new BooleanValue(true) }
                };
                SetFont(bookPart, cell, SHEET_NAME, font);

            }
            //ファイルを開く
            System.Diagnostics.Process.Start(FILE);
        }

        private static void SetFont(WorkbookPart bookPart, Cell cell, string sheet_name, Font font_to_set) {
            if (cell == null || bookPart == null) {
                return;
            }

            IEnumerable<CellFormat> cell_formats = bookPart.WorkbookStylesPart.Stylesheet.CellFormats.Elements<CellFormat>();

            CellFormat format_to;
            if (cell.StyleIndex != null) {
                CellFormat cell_xf = cell_formats.ElementAt(Convert.ToInt32(cell.StyleIndex.Value));

                int sheet_index = GetWorksheetIndex(bookPart, sheet_name);
                WorksheetPart sheet_part = GetWorksheetPart(bookPart, sheet_index);
                int referenced_count = sheet_part.Worksheet.Descendants<Cell>().Count(c => c.StyleIndex == cell.StyleIndex);

                if (referenced_count == 0) {
                    format_to = cell_xf;
                } else {
                    format_to = cell_xf.Clone() as CellFormat;

                    bookPart.WorkbookStylesPart.Stylesheet.CellFormats.Append(format_to);
                    cell.StyleIndex = new UInt32Value((uint)cell_formats.Count() - 1);
                }
            } else {
                format_to = new CellFormat();
                format_to.Alignment = new Alignment() { Vertical = new EnumValue<VerticalAlignmentValues>(VerticalAlignmentValues.Center) };
                bookPart.WorkbookStylesPart.Stylesheet.CellFormats.Append(format_to);
                cell.StyleIndex = new UInt32Value((uint)cell_formats.Count() - 1);
            }

            //Get the x:font to modify
            Font font = null;
            Fonts fonts = bookPart.WorkbookStylesPart.Stylesheet.Fonts;
            if (format_to.FontId != null && format_to.FontId.HasValue) {
                font = fonts.Elements<Font>().ElementAt(Convert.ToInt32(format_to.FontId.Value));
            } else {
                font = new Font();
                font.FontSize = new FontSize() { Val = 11 };
                fonts.Append(font);
                fonts.Count++;
                format_to.FontId = new UInt32Value((uint)fonts.Count() - 1);
            }

            //Copy the font_to_set to the font.
            CopyFont(font_to_set, font);

            bookPart.WorkbookStylesPart.Stylesheet.Save();
        }

        private static void CopyFont(Font font_from, Font font_to) {
            if (font_to.FontSize != null) {
                font_to.FontSize = new FontSize() { Val = font_to.FontSize.Val };
            }

            if (font_from.Color != null) {
                if (font_to.Color == null) {
                    font_to.Color = new Color();
                }

                if (font_from.Color.Indexed != null) {
                    font_to.Color.Indexed = new UInt32Value(font_from.Color.Indexed.Value);
                }
                if (font_from.Color.Rgb != null) {
                    font_to.Color.Rgb = new HexBinaryValue(font_from.Color.Rgb);
                }
                if (font_from.Color.Theme != null) {
                    font_to.Color.Theme = new UInt32Value(font_from.Color.Theme.Value);
                }
                if (font_from.Color.Tint != null) {
                    font_to.Color.Tint = new DoubleValue(font_from.Color.Tint.Value);
                }
            }

            if (font_from.FontName != null) {
                font_to.FontName = new FontName() { Val = font_from.FontName.Val };
            }

            if (font_from.Bold != null) {
                font_to.Bold = new Bold() { Val = new BooleanValue(font_from.Bold.Val) };
            }

            if (font_from.Italic != null) {
                font_to.Italic = new Italic() { Val = new BooleanValue(font_from.Italic.Val) };
            }

            if (font_from.Underline != null) {
                font_to.Underline = new Underline() { Val = font_from.Underline.Val };
            }

            if (font_from.Strike != null) {
                font_to.Strike = new Strike() { Val = new BooleanValue(font_from.Strike.Val) };
            }

            if (font_from.VerticalTextAlignment != null) {
                font_to.VerticalTextAlignment = new VerticalTextAlignment() { Val = font_from.VerticalTextAlignment.Val };
            }

            if (font_from.FontFamilyNumbering != null) {
                font_to.FontFamilyNumbering = new FontFamilyNumbering() { Val = font_from.FontFamilyNumbering.Val };
            }

            if (font_from.FontCharSet != null) {
                font_to.FontCharSet = new FontCharSet() { Val = font_from.FontCharSet.Val };
            }

            if (font_from.FontScheme != null) {
                font_to.FontScheme = new FontScheme() { Val = font_from.FontScheme.Val };
            }
        }
        // 以下省略...
    }
}
「以下省略」とした部分に定義されているメソッドについては 「セルの書式設定 - 表示形式」など、以前の記事をご覧ください。

はじめにフォントをセットするセルに書式がセットされているかどうかを確認します。

書式がセットされている場合、さらにそのセルから参照されているCellFormatが他のセルから参照されているかどうかを調べます。(54行目、61行目)
他のセルから参照されていない場合はそのCellFormatにフォントの設定を反映します。(62行目)
他のセルから参照されている場合はそのクローンを作成して、そのセルがこのクローンを参照するようにしたうえでこのクローンにフォントの設定を反映します。(64~66行目)

書式がセットされていない場合は新たにCellFormatを生成してこれをフォントをセットするセルから参照されるようにします。(70行目~73行目)

77行目から87行目にかけて編集するフォントを特定して(あるいは生成して)、そのフォントに引数「font_to_set」の内容を反映します。(90行目)

このコードを実行すると、セルA1, A2のフォントが以下のように変わります。

プログラム実行結果

openxmlsdk - この記事は連載の一部です
パート 14: この記事