C# Excelに出力する方法 罫線編
Category:C# 投稿日:2014年10月13日
『C# Excelに出力する方法』を読んでから、こちらの記事を読んでください。
環境
OS:Windows 7
Visual Studio:2010
Excel:2010
概要
今回は、Excelのセルに罫線を付ける方法について説明をします。
全体のプログラム
using System; using Microsoft.Office.Interop.Excel; namespace ConsoleApplication1 { class Program { static void Main() { //Excelのパス string fileName = @"C:\c_sharp\test.xlsx"; Application xlApp = new Application(); //Excelが開かないようにする xlApp.Visible = false; //指定したパスのExcelを起動 Workbook wb = xlApp.Workbooks.Open(Filename: fileName); try { //Sheetを指定 ((Worksheet)wb.Sheets[1]).Select(); } catch(Exception ex) { //Sheetがなかった場合のエラー処理 //Appを閉じる wb.Close(false); xlApp.Quit(); //Errorメッセージ Console.WriteLine("指定したSheetは存在しません."); Console.ReadLine(); //実行を終了 System.Environment.Exit(0); } //変数宣言 Range CellRange; for (int i = 1; i <= 5; i++) { //書き込む場所を指定 CellRange = xlApp.Cells[i, 1] as Range; //書き込む内容 CellRange.Value2 = "繰り返し" + i + "回目"; //罫線を付ける CellRange.Borders.get_Item(XlBordersIndex.xlEdgeBottom).LineStyle = XlLineStyle.xlDot; } //Appを閉じる wb.Close(true); xlApp.Quit(); } } }
今回追加したプログラム
//罫線を付ける CellRange.Borders.get_Item(XlBordersIndex.xlEdgeBottom).LineStyle = XlLineStyle.xlDot;
罫線を引き場所を指定
線の種類を指定