1.前言:
NPOI是Apache License 2.0的開放原始碼函式庫,提供.NET程式開發人員在無安裝Microsoft Office的環境下,讀取和操作Office 97-2007文件。

2.說明:
POI是支援JAVA的函式庫,而NPOI是支援.NET的開放原始碼,用以讀取xls, doc, ppt等檔案,在無安裝Microsoft Office的伺服器或是個人電腦上,可提供操作Office文件。
NPOI的特點:
開放的原始碼函式庫。
涵蓋大部分的Excel功能。
支援Office 97-2007的格式,例如xls, xlsx, docx。
支援輸出與輸入的功能。
支援.NET 4.0。
豐富的範例說明。

名詞說明:
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。
XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
HWPF - 提供讀寫Microsoft Word DOC格式檔案的功能。
HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。
HDGF - 提供讀Microsoft Visio格式檔案的功能。
HPBF - 提供讀Microsoft Publisher格式檔案的功能。
HSMF - 提供讀Microsoft Outlook格式檔案的功能。 

有關POI的說明可參考:
http://en.wikipedia.org/wiki/Apache_POI

NPOI軟體下載網址:
http://npoi.codeplex.com/

本範例使用版本為npoi 2.0.1 (beta1)
軟體解壓縮後,將\npoi 2.0.1 (beta1)\npoi\dotnet3.5的DLL檔複製到自己專案的bin目錄下

加入參考: NPOI.dll, NPOI.OOXML.dll
加入命名空間:

using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;

程式碼:

//範例一,簡單產生Excel檔案的方法
private void CreateExcelFile()
{
	//建立Excel 2003檔案
	IWorkbook wb = new HSSFWorkbook();
	ISheet ws = wb.CreateSheet("Class");

	////建立Excel 2007檔案
	//IWorkbook wb = new XSSFWorkbook();
	//ISheet ws = wb.CreateSheet("Class");

	ws.CreateRow(0);//第一行為欄位名稱
	ws.GetRow(0).CreateCell(0).SetCellValue("name");
	ws.GetRow(0).CreateCell(1).SetCellValue("score");
	ws.CreateRow(1);//第二行之後為資料
	ws.GetRow(1).CreateCell(0).SetCellValue("abey");
	ws.GetRow(1).CreateCell(1).SetCellValue(85);
	ws.CreateRow(2);
	ws.GetRow(2).CreateCell(0).SetCellValue("tina");
	ws.GetRow(2).CreateCell(1).SetCellValue(82);
	ws.CreateRow(3);
	ws.GetRow(3).CreateCell(0).SetCellValue("boi");
	ws.GetRow(3).CreateCell(1).SetCellValue(84);
	ws.CreateRow(4);
	ws.GetRow(4).CreateCell(0).SetCellValue("hebe");
	ws.GetRow(4).CreateCell(1).SetCellValue(86);
	ws.CreateRow(5);
	ws.GetRow(5).CreateCell(0).SetCellValue("paul");
	ws.GetRow(5).CreateCell(1).SetCellValue(82);
	FileStream file = new FileStream(@"d:\tmp\npoi.xls", FileMode.Create);//產生檔案
	wb.Write(file);
	file.Close();
}

//範例二,DataTable轉成Excel檔案的方法
private void DataTableToExcelFile(DataTable dt)
{
	//建立Excel 2003檔案
	IWorkbook wb = new HSSFWorkbook();
	ISheet ws;

	////建立Excel 2007檔案
	//IWorkbook wb = new XSSFWorkbook();
	//ISheet ws;

	if (dt.TableName != string.Empty)
	{
		ws = wb.CreateSheet(dt.TableName);
	}
	else
	{
		ws = wb.CreateSheet("Sheet1");
	}

	ws.CreateRow(0);//第一行為欄位名稱
	for (int i = 0; i < dt.Columns.Count; i++)
	{
		 ws.GetRow(0).CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
	}

	for (int i = 0; i < dt.Rows.Count; i++)
	{
		ws.CreateRow(i + 1);
		for (int j = 0; j < dt.Columns.Count; j++)
		{
			ws.GetRow(i+1).CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
		}
	}
	
	FileStream file = new FileStream(@"d:\tmp\npoi.xls", FileMode.Create);//產生檔案
	wb.Write(file);
	file.Close();
}
arrow
arrow
    文章標籤
    C# NPOI Excel
    全站熱搜

    西夏普 發表在 痞客邦 留言(4) 人氣()