1. 程式人生 > >NOPI Excel 讀取公式生成後的資料

NOPI Excel 讀取公式生成後的資料

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace PortalPBIRS.Models
{
    class ExcelHelper : IDisposable
    {
        private string fileName = null
; //檔名 private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; readonly int EXCEL03_MaxRow = 65535; public ExcelHelper(string fileName) { this.fileName = fileName; disposed = false; }
/// <summary> /// 將excel中的資料匯入到DataTable中 /// </summary> /// <param name="sheetName">excel工作薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataTable ExcelToDataTable(string
sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);//讀取檔案 if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName);//獲取檔案的分頁 if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { int k = 0, cellCount = 0; IRow firstRow = sheet.GetRow(0);//獲取第一行 while (firstRow == null) { firstRow = sheet.GetRow(++k);//排除空行,找到第一個有字元的行 } if (isFirstRowColumn)//第一行是列名 { cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = ""; if (cell.CellType == CellType.Formula) { cellValue = cell.RichStringCellValue.String; } else { cellValue = cell.StringCellValue; } if (cellValue != null) { DataColumn column = new DataColumn(cellValue.Replace("\n","")); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else// 第一行不是列名 { int max = 0; for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)// 找到所有行中最多字元 { if (sheet.GetRow(i) == null) continue; max = (sheet.GetRow(i).LastCellNum > max) ? sheet.GetRow(i).LastCellNum : max; } cellCount = max; for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { DataColumn column = new DataColumn(); data.Columns.Add(column); } startRow = sheet.FirstRowNum; } //最後一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i)//將從檔案中獲取的資料儲存到DataTable中 { IRow row = sheet.GetRow(i); if (row == null) { continue; //沒有資料的行預設是null } DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { //同理,沒有資料的單元格都預設是null if (row.GetCell(j) != null) { if (row.GetCell(j).CellType == CellType.Formula) { row.GetCell(j).SetCellType(CellType.String); dataRow[j]= row.GetCell(j).RichStringCellValue.String; } else { dataRow[j] = row.GetCell(j).ToString(); } } } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } /// <summary> /// 將DataTable轉換為excel2003格式。 /// </summary> /// <param name="dt"></param> /// <returns></returns> public byte[] DataTableToExcel(DataTable dt, string sheetName) { IWorkbook book = new HSSFWorkbook(); if (dt.Rows.Count < EXCEL03_MaxRow) DataWrite2Sheet(dt, 0, dt.Rows.Count - 1, book, sheetName); else { int page = dt.Rows.Count / EXCEL03_MaxRow; for (int i = 0; i < page; i++) { int start = i * EXCEL03_MaxRow; int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - 1; DataWrite2Sheet(dt, start, end, book, sheetName + i.ToString()); } int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow; DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, lastPageItemCount, book, sheetName + page.ToString()); } MemoryStream ms = new MemoryStream(); book.Write(ms); return ms.ToArray(); } private void DataWrite2Sheet(DataTable dt, int startRow, int endRow, IWorkbook book, string sheetName) { ISheet sheet = book.CreateSheet(sheetName); IRow header = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = header.CreateCell(i); string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName; cell.SetCellValue(val); } int rowIndex = 1; for (int i = startRow; i <= endRow; i++) { DataRow dtRow = dt.Rows[i]; IRow excelRow = sheet.CreateRow(rowIndex++); for (int j = 0; j < dtRow.ItemArray.Length; j++) { excelRow.CreateCell(j).SetCellValue(dtRow[j].ToString()); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (fs != null) fs.Close(); } fs = null; disposed = true; } } } }
row.GetCell(j).CellType == CellType.Formula