LoginSignup
1
1

More than 1 year has passed since last update.

【C#】NPOIを使って「.xls」と「.xlsx」に対して罫線を引く

Posted at

概要

  • 「.xls」と「.xlsx」に対して罫線を引く
  • 以下に記載コードは.xlsと.xlsx共通コード

使用バージョン

  • Npoi 2.5.3
  • .Netframwork4.7.2
  • Windowsフォームアプリケーションで実装

セルに対して罫線を引くソース

  • ファイルの読み込みを含めて以下に記載
  • 以下結果

2021-06-04_16h35_56.png

  • 実際に引いたコード
sample.cs
using NPOI.SS.UserModel;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;

/// filepathに「.xls」or 「.xlsx」のファイルパスを渡してください
public void WriteCell(string filepath)
{
    book = WorkbookFactory.Create(filepath);
    var sheet = book.GetSheetAt(0);

    IRow row = sheet.CreateRow(5);
    ICell cell = row.CreateCell(5);
    cell.SetCellType(CellType.String);
    cell.SetCellValue("testssss");

    ICellStyle cellStyle = sheet.Workbook.CreateCellStyle();

    //セルの上に引く
    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
    cellStyle.TopBorderColor = IndexedColors.Aqua.Index;

    //セルの下に引く
    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
    cellStyle.BottomBorderColor = IndexedColors.Green.Index;

    //セルの左に引く
    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
    cellStyle.LeftBorderColor = IndexedColors.Black.Index;

    //セルの右に引く
    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
    cellStyle.RightBorderColor = IndexedColors.LightBlue.Index;

    //セルの斜めに引く
    cellStyle.BorderDiagonal = NPOI.SS.UserModel.BorderDiagonal.Forward;
    cellStyle.BorderDiagonalLineStyle = NPOI.SS.UserModel.BorderStyle.Thin;
    cellStyle.BorderDiagonalColor = IndexedColors.Black.Index;

    //セルのスタイルを保存
    cell.CellStyle = cellStyle;

    //ブックを保存
    using (var fs = new FileStream(filepath, FileMode.Create))
    {
        book.Write(fs);
    }

    var result = MessageBox.Show("処理しました。ファイルを開きますか?","確認",MessageBoxButtons.YesNo,MessageBoxIcon.Information);
    if (result == DialogResult.Yes)
    {
        Process.Start(filepath);    
    }
}

注意点

  • 上記のコードで斜めを引くときに「.xlsx」だと斜めだけでなく、どこかの罫線を引いてあげないと罫線が引かれない

参考文書

1
1
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
1
1