C# 使用NPOI 把資料寫到excel檔案(xlsx)


10X10矩陣統計與列表


利用 NPOI 套件產生如上圖的內容到一個excel檔案
本案例 C# 為 .Net 4.5 ,NPOI 為 2.5.1 版

程式碼如下:

// 樣式元件
DefXSSFstyle style = new DefXSSFstyle();

IWorkbook wb = new XSSFWorkbook();
// 建立分頁賦予分頁名稱
ISheet ws1 = wb.CreateSheet("統計表");
// 建立數字陣列 10 X 10
for(int i = 1; i<= 10; i++)
{
    IRow row0 = ws1.CreateRow(i - 1);
    for (int j = 1; j <= 10; j++)
    {
        ICell cell0 = row0.CreateCell(j - 1);
        cell0.SetCellValue(((i - 1) * 10) + j);
    }
}

// 建立合計
ASCIIEncoding aSCII = new ASCIIEncoding();
XSSFCellStyle cssf = style.Field09(wb);
IRow subRow = ws1.CreateRow(ws1.LastRowNum + 1);
for(int k = 1; k <= 10; k++)
{
    // 設定公式
    string headChar = aSCII.GetString(new byte[] { (byte)(64 + k) });
    ICell subCell = subRow.CreateCell(k - 1);
    subCell.SetCellFormula("SUM(" + headChar + "1:" + headChar + ws1.GetRow(0).LastCellNum.ToString() + ")");
    // 加入樣式
    subCell.CellStyle = cssf;
}

// 儲存
string saveFile = savePath + "\\NPOI_RES.xlsx";
// 使用檔案複寫
FileStream fs = new FileStream(saveFile, FileMode.Create, FileAccess.Write);
wb.Write(fs);








上面順序為:
1.產生 WorkBook 
2.利用 WorkBook 產生 WorkSheet 
3.利用 WorkSheet 產生 IRow 
3.利用 IRow 產生 ICell
4.在 Cell 上設定資料內容(文字/數值/公式),或加上樣式(Style) 

留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式