資源簡介
實現NPOI對EXECL文件的導入、顯示和導出!
代碼片段和文件信息
using?NPOI.HSSF.UserModel;
using?NPOI.HSSF.Util;
using?NPOI.SS.Formula.Functions;
using?NPOI.SS.UserModel;
using?NPOI.XSSF.UserModel;
using?System;
using?System.Collections.Generic;
using?System.ComponentModel;
using?System.Data;
using?System.Drawing;
using?System.IO;
using?System.Reflection;
using?System.Text;
using?System.Windows.Forms;
namespace?TestNPOI
{
????public?partial?class?Form1?:?Form
????{
????????public?Form1()
????????{
????????????InitializeComponent();
????????}
????????public?static?DataTable?GetDS(string?fileName?bool?isFirstRowColumn)
????????{
????????????IWorkbook?workbook?=?null;
????????????FileStream?fs?=?null;
????????????bool?disposed;
????????????ISheet?sheet?=?null;
????????????string?sheetName?=?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)
????????????????{
????????????????????IRow?firstRow?=?sheet.GetRow(7);
????????????????????int?cellCount?=?firstRow.LastCellNum;?//一行最后一個cell的編號?即總的列數
????????????????????if?(isFirstRowColumn)
????????????????????{
????????????????????????for?(int?i?=?firstRow.FirstCellNum;?i?????????????????????????{
????????????????????????????ICell?cell?=?firstRow.GetCell(i);
????????????????????????????if?(cell?!=?null)
????????????????????????????{
????????????????????????????????string?cellValue?=?cell.StringCellValue;
????????????????????????????????if?(cellValue?!=?null)
????????????????????????????????{
????????????????????????????????????DataColumn?column?=?new?DataColumn(cellValue);
????????????????????????????????????data.Columns.Add(column);
????????????????????????????????}
????????????????????????????}
????????????????????????}
????????????????????????startRow?=?sheet.FirstRowNum?+?1;
????????????????????}
????????????????????else
????????????????????{
????????????????????????startRow?=?sheet.FirstRowNum;
????????????????????}
????????????????????//最后一列的標號
????????????????????int?rowCount?=?sheet.LastRowNum;
????????????????????for?(int?i?=?startRow;?i?<=?rowCount;?++i)
????????????????????{
????????????????????????IRow?row?=?sheet.GetRow(i);
???????
評論
共有 條評論