[EXCEL] NPOI 基本範例

 

NPOI 官網有一些基本範例可參考,以下是 XSSF 範例

一、創立檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;

namespace NPOI.Examples.XSSF.CreateEmptyWorkbook
{
class Program
{
static void Main(string[] args)
{
IWorkbook workbook = new XSSFWorkbook();
workbook.CreateSheet("Sheet 1");
workbook.CreateSheet("Sheet 2");
workbook.CreateSheet("Sheet 3");

FileStream sw = File.Create("test.xlsx");
workbook.Write(sw);
sw.Close();

Console.WriteLine("File 'test.xls' generated");
Console.ReadLine();
}
}
}

說明:
1、程式結果為新增三張工作表,並將其存成 test.xls 檔。

二、資料寫入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* ================================================================
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* NPOI Examples: https://github.com/nissl-lab/npoi-examples
* ==============================================================*/

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

namespace CreateHeaderFooterInXlsx
{
class Program
{
static void Main(string[] args)
{
IWorkbook workbook = new XSSFWorkbook();
ISheet s1 = workbook.CreateSheet("Sheet1");
s1.CreateRow(0).CreateCell(1).SetCellValue(123);

//set header text
s1.Header.Left = HSSFHeader.Page; //Page is a static property of HSSFHeader and HSSFFooter
s1.Header.Center = "This is a test sheet";
//set footer text
s1.Footer.Left = "Copyright Nissl Lab";
s1.Footer.Right = "created by NPOI team";
using (FileStream sw = File.Create("test.xlsx"))
{
workbook.Write(sw);
}
}
}
}

說明:
1、程式結果為新增一張工作表,並將其中一 cell 寫入值,
設定其頁首頁尾樣式,並存成 excel 檔。

參考資料:
npoi

npoi-examples