概要
前回記事より。
C#でのExcel操作取得編 - Status Code 303 - See Other
例のごとくClosed XMLを使って遊んでみる。今回は、Excelのセル操作をC#で実現する方法のメモ。
中々文献が見つからないが、触ってみるとだんだんと使いやすさが分かってくる。
テスト用のコード
今回紹介するのはセル操作のみなので、A2のcell参照を取得して、それに操作してセーブする流れとする。
// 編集用のファイルを C:\\Users\\hoshikouki\\sample.xlsx に置いている想定。 using (var book = new XLWorkbook("C:\\Users\\hoshikouki\\sample.xlsx")) { var ws = book.Worksheet("Sheet1"); var cell = ws.Cell("A2"); // //ここに下記コード張って楽しんだください!. // // セーブ book.SaveAs("C:\\Users\\hoshikouki\\sample2.xlsx"); }
セル操作
データ入力規則(リスト)
cell.DataValidation.List(ws.Range("$E$1:$E$4"));
コメント追加
cell.Comment.AddText("コメント!");
データ形式変更
cell.DataType = XLCellValues.Text; //cell.DataType = XLCellValues.Number; //cell.DataType = XLCellValues.DateTime; //cell.DataType = XLCellValues.TimeSpan;
データ表示方法変更
cell.Style.DateFormat.Format = "yyyyMMdd"; // cell.Style.NumberFormat.Format = "(-###)";
文字色変更
cell.Style.Fill.BackgroundColor = XLColor.Gold;
//cell.Style.Fill.BackgroundColor = XLColor.NoColor;
背景色変更
cell.Style.Fill.BackgroundColor = XLColor.Gold;
//cell.Style.Fill.BackgroundColor = XLColor.NoColor;
セル周りの線
cell.Style.Border.BottomBorder = XLBorderStyleValues.DashDot; cell.Style.Border.BottomBorderColor = XLColor.Red; // cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thick; // cell.Style.Border.OutsideBorderColor = XLColor.Red;
セル内の表示場所
// 垂直方向操作 cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Bottom; // 水平方向操作 cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right; // セル内に収まるように文字サイズを調整して表示 cell.Style.Alignment.ShrinkToFit = true; // 折り返して全体を表示する cell.Style.Alignment.WrapText = true;