目標:
此簡單例子將使用EPPlus建立一個如下圖之結果,並設定好後續所需的開發環境。建立步驟
1.先下載EPPLus最新版本。並解壓縮。2.開啟新的VS.NET 專案,
在VS.NET 專案將EPPLus參考。
3.檢查 Solution Explorer 是否如圖所示。
因為需要System.Web 的參考,請特別注意是否有,
不然編譯可能無法成功。
4.請記得將framework 改為.NET Framework 4.0,不要使用Client Profile。
C# 主要程式碼
// Using 區
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;
//建立xlsx 檔的函數
public void Create()
{
System.IO.FileInfo newfile = new System.IO.FileInfo(_filePath);
using (var package = new ExcelPackage(newfile))
{
ExcelWorksheet worksheet
= package.Workbook.Worksheets.Add("週報1");
setFontColorWhite(worksheet, 1, 1, 1, 12);
worksheet.Cells[1, 1, 1, 12].Merge = true;
worksheet.Cells[1, 1, 1, 12].Value = "週報";
worksheet.Cells[1, 1, 1, 12].Style.HorizontalAlignment
= ExcelHorizontalAlignment.Center;
worksheet.Cells[1, 1, 1, 12].Style.Font.Size = 12;
worksheet.Cells[1, 1, 1, 12].Style.Font.Color.SetColor(Color.White);
package.Save();
}
}
//設定Title底色及字顏色的函數
private void setFontColorWhite
(ExcelWorksheet ws, int fromRow, int toRow, int fromCol, int toCol)
{
using (var range = ws.Cells[fromRow, fromCol, toRow, toCol])
{
range.Style.Font.Bold = true;
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(Color.Black);
range.Style.Font.Color.SetColor(Color.White);
}
}
沒有留言:
張貼留言