NPOI的匯入匯出EXCEL示範

2021-09-24 09:35:35 字數 2709 閱讀 6704

using system;

using system.data;

using system.diagnostics;

using system.io;

using system.windows.forms;

using npoi.hssf.usermodel;

using npoi.ss.usermodel;

using npoi.xssf.usermodel;

namespace npoi匯入匯出

filestream fs = new filestream(s***.filename, filemode.open, fileaccess.read);

iworkbook book;

if (s***.filterindex == 1)

else

int exceptiontableindex = 0;

int exceptionrowindex = 0;

int exceptioncolumnindex = 0;

int sheetcount = book.numberofsheets;

tryfor (int i = 1; i <= sheet.lastrownum; i++)

if (cell.cachedformularesulttype == celltype.string)

}else

}else}}

ds.tables.add(dt);}}

catch (exception theexception)

**行列有錯誤!",exceptiontableindex,exceptionrowindex,exceptioncolumnindex,theexception.message));

}return ds;

}/// /// 匯出excel

///

/// 資料**資料來源

/// 資料來源列名集合

public static void exportexcel(datatable datatable, string colnames)

iworkbook book;

if (s***.filterindex == 1)

else

isheet sheet = book.createsheet("sheet1");

// 新增表頭

irow row = sheet.createrow(0);

int index = 0;

for (int n = 0; n < datatable.columns.count; n++)

// 新增資料

for (int i = 0; i < datatable.rows.count; i++)

}// 寫入

memorystream ms = new memorystream();

book.write(ms);

using (filestream fs = new filestream(s***.filename, filemode.create, fileaccess.write))

ms.close();

ms.dispose();

process.start(s***.filename);

}/// /// 匯出excel

///

/// 關於行索引和行名的字典

/// 關於列索引和列名的字典

/// npoi**中的單元格模型集合

public static void exportexcel(dictionaryrowdictionary, dictionarycolumndictionary, listthenpoimodels)

iworkbook book;

if (s***.filterindex == 1)

else

isheet sheet = book.createsheet("sheet1");

// 新增表頭

irow row = sheet.createrow(0);

for (int n = 0; n <= columndictionary.count; n++)

else

icell cell = row.createcell(n);

cell.setcelltype(celltype.string);

cell.setcellvalue(tempvalue);

}// 新增資料

for (int i = 1; i <= rowdictionary.count; i++)

else

}icell cell = row.createcell(j);

cell.setcelltype(celltype.string);

cell.setcellvalue(tempvalue);}}

// 寫入

memorystream ms = new memorystream();

book.write(ms);

using (filestream fs = new filestream(s***.filename, filemode.create, fileaccess.write))

ms.close();

ms.dispose();

process.start(s***.filename);}}

}

excelhelper.cs

npoi匯入匯出excel

1.匯入 將datatable資料匯入到excel中 要匯入的資料 datatable的列名是否要匯入 要匯入的excel的sheet的名稱 匯入資料行數 包含列名那一行 public int datatabletoexcel datatable data,string sheetname,bool...

Npoi匯入匯出Excel操作

datatable匯出excel private static void gridtoexcelbynpoi datatable dt,string strexcelfilename icellstyle cellstyle workbook.createcellstyle 為避免日期格式被exce...

NPOI實現 Excel匯入匯出

實現物件集合寫入到excel和excel資料讀出到物件集合的功能 自定義列屬性 public class columnattribute attribute public columnattribute string columnname 時間格式 public class datetimeform...