NPOI實現 Excel匯入匯出

2021-10-03 18:32:40 字數 2883 閱讀 7224

實現物件集合寫入到excel和excel資料讀出到物件集合的功能

///

/// 自定義列屬性

///

public class columnattribute:attribute

public columnattribute(string columnname)

}///

/// 時間格式

///

public class datetimeformateattribute : attribute

public datetimeformateattribute(string formate)

}///

/// 從excel中讀取資料

///

///

public class excelhelperwhere t : class

type t = typeof(t);

assembly ass = assembly.load(t.assembly.fullname);

var propertyes = t.getproperties();

dictionarypropertycolumnnames = new dictionary();  //列明屬性名

foreach (var pro in propertyes)

具有重複的column屬性", t.fullname));

}propertycolumnnames.add(columnname, pro);

}if(pro.getcustomattributes(typeof(rowindexattribute),false).length>0)

}for (int i = 0; i < 1; i++)

if (columnnames.contains(name))

", name));

}columnnames.add(name);

}for (int index = 1; index <= sheet.lastrownum; index++)  //遍歷excel每一行資料

irow excelrow = sheet.getrow(index);

for (int j = 0; j < columnaccount; j++)  //遍歷每一行的每一列

string columnname = columnnames[j];

if (propertycolumnnames.containskey(columnname))

continue;

}if (profullname.contains("int32"))

continue;

}if (profullname.contains("string"))

if (profullname.contains("int64"))

continue;

}if (profullname.contains("decimal"))

continue;

}if (profullname.contains("datetime"))

else if (datetime.tryparse(cell.tostring(), out v5))

continue;

}if (profullname.contains("boolean"))

continue;

}if (profullname.contains("single"))

continue;

}if (profullname.contains("double"))}}

}}results.add(obj);}}

return results;

}public static datatable getdatatablefromexcel( string filepath)

datatable dt = new datatable();

isheet sheet = workbook.getsheetat(0);

irow firstrow = sheet.getrow(0);

//獲取excel列表列的總數

int columns = 0;

while (true)

columns++;

dt.columns.add(cell.tostring());

}for (int i = 0; i < sheet.lastrownum; i++)

else}}

dt.rows.add(row);

}return dt;

}public static iworkbook getdata(string filepath)

iworkbook workbook = null;

using (filestream fs = new filestream(filepath, filemode.open, fileaccess.read))

return workbook;

}///

/// 將資料寫入到excel中去

///

///

/// ]

///

/// 返回檔案路徑

workbook.write(fs);

fs.flush();

}return filepath;

}public class person

[column("生日")]

[datetimeformate("yyyy-mm-dd")]

public datetime birthday

}public  void main(object args)

產生的結果

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...

C 使用NPOI實現Excel的匯入匯出

excel小幫手 public static class excelhelper if ofd.showdialog dialogresult.ok else iworkbook workbook null using var fs file.openread filename if path.ge...