1.使用場景:
在不安裝Office組件包的情況下,操作Excel文件(.xlsx)。以前做過的好幾個項目中,都需要對Excel文件處理,特別是將統計成果按照一定的格式和樣式輸出到Excel中,或將固定格式的Excel數據導入到系統,這種需求非常常見,以前的做法主要是基於Office組件進行二次開發。但這種做法存在一定的缺陷,(1) 部署比較麻煩,所有的部署機上都必須安裝Office。(2)好多新手在使用Office開發時,對自動生成的office組件包裝類理解不深,導致在項目移植的過程中引起了很多的問題。
2.EPPlus庫的使用:
EPPlus是一個能不依賴於Office而獨立讀寫操作Excel2007/2010的.net類庫,主要是操作Excel的xlsx文件。
官方下載地址:http://epplus.codeplex.com/
EPPlus提供的功能包括:
Cell Ranges 單元格範圍
Cell Styling 單元格樣式,包括:邊框、顏色、填充、字體、顯示格式(Number)、靠邊。
Charts 統計圖表
Picture 圖片
Shapes
Comments
Tables 表格
Protection 協議
Encryption 加密
Pivot Tables透視表
Conditional Formatting、VBA、Enumeration Of Cell 支持Linq。等。
2.應用實例
注意:在使用之前必須添加兩個引用,這兩個命名空間都在EPPlus.dll庫中。
using OfficeOpenXml;
using OfficeOpenXml.Style;
(1)【寫】這是項目中用到的創建一個.xlsx文件,並將統計結果到處到此.xlsx文件中。
/// <summary>
/// 統計信息輸出到excel文件中,創建本地緩存。
/// </summary>
/// <param name="singleDataTable">單程</param>
/// <param name="doubleTable">往返</param>
/// <returns>ture,false</returns>
private bool ExportToExcel(DataTable singleDataTable, DataTable doubleTable)
{
ExcelPackage excelPackage = new ExcelPackage();
#region 單程
ExcelWorksheet single_Sheet = excelPackage.Workbook.Worksheets.Add("single_Sheet");
single_Sheet.Name = "單程航班";
single_Sheet.Cells.Style.Font.Size = 9;
single_Sheet.Cells.Style.Font.Name = "微軟雅黑";
single_Sheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
int columsCount = singleDataTable.Columns.Count;
int rowIndex = 0;
++rowIndex; //在worksheet中添加新行
for (int i = 0; i < columsCount; i++)
{
single_Sheet.Cells[rowIndex, i + 1].Value = singleDataTable.Columns[i].ColumnName;
single_Sheet.Cells[rowIndex, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
single_Sheet.Cells[rowIndex, i + 1].Style.Font.Bold = true;
}
++rowIndex;//excel第一行用來存儲表格頭,從第二行開始存儲數據。
for (int i = 0; i < singleDataTable.Rows.Count; i++)
{
for (int j = 0; j < columsCount; j++)
{
single_Sheet.Cells[rowIndex + i, j + 1].Value = singleDataTable.Rows[i][j].ToString();
}
}
#endregion
#region 往返
ExcelWorksheet double_Sheet = excelPackage.Workbook.Worksheets.Add("double_Sheet");
double_Sheet.Name = "往返航班";
double_Sheet.Cells.Style.Font.Size = 9;
double_Sheet.Cells.Style.Font.Name = "微軟雅黑";
double_Sheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
rowIndex = 0;
++rowIndex; //在worksheet中添加新行
for (int i = 0; i < columsCount; i++)
{
double_Sheet.Cells[rowIndex, i + 1].Value = doubleTable.Columns[i].ColumnName;
double_Sheet.Cells[rowIndex, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
double_Sheet.Cells[rowIndex, i + 1].Style.Font.Bold = true;
}
++rowIndex;
for (int i = 0; i < doubleTable.Rows.Count; i++)
{
for (int j = 0; j < columsCount; j++)
{
double_Sheet.Cells[rowIndex + i, j + 1].Value = doubleTable.Rows[i][j].ToString();
}
}
#endregion
#region 輸出到執行目錄
try
{
this.cacheFileName = string.Format("航線查詢明細日報v{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
if (Directory.Exists(cacheDirectory) == false)
{
Directory.CreateDirectory(cacheDirectory);
}
string fullpath = cacheDirectory + this.cacheFileName;
FileStream fileStream = new FileStream(fullpath, FileMode.Create);
using (fileStream)
{
byte[] fileBytes = excelPackage.GetAsByteArray();
fileStream.Write(fileBytes, 0, fileBytes.Length);
fileStream.Close();
}
}
catch
{
return false;
}
return true;
#endregion
}
(2) 【讀】讀取.xslx的文件。
/// <summary>
/// 將統計結果發送到指定郵箱。
/// </summary>
/// <returns></returns>
private bool SendEmail()
{
ExcelPackage excelPackage = new ExcelPackage(new FileInfo(this.cacheDirectory + this.cacheFileName));
string mailMessagaBodyToHtml = ConvertExcelToHtml(excelPackage.Workbook.Worksheets);
string smtpClientHost=@"mail.ly.com";
string networkCredentialName="my08567";
string networkCredentialPassword= @"123qwe!@#";
string fromMailAddress="[email protected]";
string toMailAddress="[email protected];[email protected];[email protected]";
string duplicateMailAddress="[email protected];[email protected]";
string subject="航線查詢日報表";
string body=ConvertExcelToHtml(excelPackage.Workbook.Worksheets);
bool isHtml=true;
MemoryStream attachmentSteam= new MemoryStream(excelPackage.GetAsByteArray());;
string attachmentFileName = DateTime.Today.ToString("yyyyMMdd") + "航線查詢明細日報.xlsx";
try
{
SendEmailHelper.SendEMailNet(smtpClientHost, networkCredentialName, networkCredentialPassword, fromMailAddress,
toMailAddress, duplicateMailAddress, subject, body, isHtml, attachmentSteam, attachmentFileName);
return true;
}
catch
{
return false;
}
}
在網上搜集的過程中,還發現對Excel文件格式的操作,還有一下幾個開源組件可以使用ExcelLibrary,NPOI等。