//加入擴充方法: SetQuickStyle,指定前景色/背景色/水平對齊
private static void SetQuickStyle(this ExcelRange range,
Color foreColor,
Color bgColor = default(Color),
ExcelHorizontalAlignment hAlign = ExcelHorizontalAlignment.Left)
{
range.Style.Font.Color.SetColor(foreColor);
if (bgColor != default(Color))
{
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(bgColor);
}
range.Style.HorizontalAlignment = hAlign;
}
/// <summary>
/// 將目錄下的目錄檔案結構匯出成Excel工作表
/// </summary>
/// <param name="dirPath">要匯出的目錄路徑</param>
/// <param name="excelPath">匯出Excel路徑</param>
/// <param name="filter">過濾函數,傳入Path進行判斷,傳回true時表排除</param>
/// <returns></returns>
public static void WebTreeToExcel(
string dirPath, string excelPath,
Func<string, bool> filter = null)
{
//將目錄結構整理成清單
List<WebItem> list = new List<WebItem>();
explore(list, dirPath, 0);
//建立Excel
using (ExcelPackage p = new ExcelPackage())
{
ExcelWorksheet sheet = p.Workbook.Worksheets.Add("Site Tree");
int colIdx = 1;
foreach (string colName in "Path;File;Description".Split(';'))
{
sheet.Cells[1, colIdx++].Value = colName;
}
//修改標題列Style
sheet.Cells[1, 1, 1, 3].SetQuickStyle(Color.Yellow, Color.Green,
ExcelHorizontalAlignment.Center);
int rowIdx = 2;
foreach (var item in list)
{
//若bypass檢測傳回true,則略過該筆
if (filter != null && filter(item.Path))
continue;
//將Path放在第一欄(稍後隱藏)
sheet.Cells[rowIdx, 1].Value = item.Path;
//存入檔名或目錄名
sheet.Cells[rowIdx, 2].Value =
new String(' ', item.Layer * 4) + item.Name;
if (item.IsFolder)
{
sheet.Cells[rowIdx, 2].SetQuickStyle(Color.Blue);
}
rowIdx++;
}
//第一欄隱藏
sheet.Column(1).Hidden = true;
//自動伸縮欄寬
sheet.Column(2).AutoFit();
sheet.Column(2).Width += 2;
sheet.Column(3).Width = 50;
//寫入檔案
p.SaveAs(new FileInfo(excelPath));
}