您可以用NPOI .xls和.XLSX扩展读取Excel文件,你只需要添加下一个在使用部分
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
的主要的是,在打开文件时,必须让你用此时,相应componente延伸部之间进行区分,并使用ISheet接口,这样可以独立地引用该文件的扩展名的片
//We get the file extension
fileExt = Path.GetExtension(fileName);
//Declare the sheet interface
ISheet sheet;
//Get the Excel file according to the extension
if (fileExt.ToLower() == ".xls")
{
//Use the NPOI Excel xls object
HSSFWorkbook hssfwb;
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
hssfwb = new HSSFWorkbook(file);
}
//Assign the sheet
sheet = hssfwb.GetSheet(sheetName);
}
else //.xlsx extension
{
//Use the NPOI Excel xlsx object
XSSFWorkbook hssfwb;
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
}
//Assign the sheet
sheet = hssfwb.GetSheet(sheetName);
}
一旦你的Excel对象,你只需要阅读它(在NPOI行和列的从零开始的)
//Loop through the rows until we find an empty one
for (int row = 0; row <= sheet.LastRowNum; row++)
{
//Get the cell value
string cellValue = sheet.GetRow(row).GetCell(0).ToString().Trim(); //In the method GetCell you specify the column number you want to read, in the method GetRow you spacify the row
string cellValue2 = sheet.GetRow(row).GetCell(0).StringCellValue.Trim();
}
要读取,你可以使用的ToString()方法或StringCellValue财产细胞瓦鲁尔足球俱乐部,但请注意,StringCellValue仅适用于字符串单元格,数字和日期单元格会引发异常。
是的,我经常导入NPOI的'.xlsx'文件 - 绝对没有问题 - 只要去代码吧! –
但是当我尝试使用.xlsx加载文件时,它无法导入? – Ganeshja
根据[本博客文章](http://www.zachhunter.com/2010/05/read-xlsx-data-for-npoi/),NPOI支持版本1.6以上的'.xlsx'。该博客文章还显示了NPOI –