先到NuGet套件管理員下載安裝EPPlus
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;
using System.IO;
namespace EPPlusDemo
{
class Program
{
static void Main(string[] args)
{
//檔案路徑
string filePath = @"C:\csharp\ExcelTest.xlsx";
//檢查檔案是否存在,存在則刪除
if (File.Exists(filePath))
{
File.Delete(filePath);
}
//建立ExcelPackge物件
using (ExcelPackage p = new ExcelPackage())
{
//建立test1工作表
ExcelWorksheet sheet = p.Workbook.Worksheets.Add("test1");
//用Row Col表示位置
sheet.Cells[1, 1].Value = "標題一";
//用Excel欄位表示位置
sheet.Cells["B1"].Value = "欄位二";
for (int i = 3; i <= 5; i++)
{
//From Row,From Col,ToRow,To Col表示範圍
sheet.Cells[1, 3, 1, 5].Value = "欄位" + i;
}
//寫值
for (int i = 2; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
sheet.Cells[i, j].Value = $"[{i},{j}]";
}
}
//設定框線
sheet.Cells[1, 1, 5, 5].Style.Border.Top.Style = ExcelBorderStyle.Thin;
sheet.Cells[1, 1, 5, 5].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
sheet.Cells[1, 1, 5, 5].Style.Border.Left.Style = ExcelBorderStyle.Thin;
sheet.Cells[1, 1, 5, 5].Style.Border.Right.Style = ExcelBorderStyle.Thin;
//標題背景顏色
ExcelRange header = sheet.Cells["A1:E1"];
header.Style.Fill.PatternType = ExcelFillStyle.Solid;
header.Style.Fill.BackgroundColor.SetColor(Color.LightGreen);
using (FileStream fileOutput = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
//存檔
p.SaveAs(fileOutput);
}
}
}
}
}
除了框線與顏色設定外,可設定的項目還有很多,例如合併儲存格,字型,輸入公式等等。
附上EPPlus官網。
沒有留言:
張貼留言