NPOI:如何读取没有标题的excel单元格

时间:2014-02-24 08:53:53

标签: c# excel parsing npoi

我正在尝试使用NPOI从.xlsx Excel文件中提取TEXT。

下面是示例Excel文件的链接:

http://s29.postimg.org/i7rtrucaf/excel_File.png

函数ExcelDocumentToText提取所有单元格值,但不提取包含INR的单元格(单元格F2)

    static void ExcelDocumentToText(string path = @"..\..\..\01.xlsx")
    {
        StringBuilder textOfExcelDocumnet = new StringBuilder();
        ISheet sheet = null; IRow headerRow = null; IEnumerator allRows = null;

        using (FileStream ExcelFile = new FileStream(path, FileMode.Open, FileAccess.Read))
            xlsReaderObject = new XSSFWorkbook(ExcelFile);

        for (int j = 0; j < xlsReaderObject.Count; j++)
        {
            sheet = xlsReaderObject.GetSheetAt(j);
            for (int p = 0; p < sheet.LastRowNum; p++)
            {
                headerRow = sheet.GetRow(p);
                if (headerRow != null)
                    break;
            }
            allRows = sheet.GetRowEnumerator();

            int colCount = headerRow.LastCellNum;

            while (allRows.MoveNext())
            {
                //IRow row = (HSSFRow)rows.Current;
                IRow row = (XSSFRow)allRows.Current;
                for (int i = 0; i < colCount; i++)
                {
                    ICell cell = row.GetCell(i);
                    if (cell != null)
                        textOfExcelDocumnet.AppendLine(cell.ToString());
                }
            }
            sheet = null; headerRow = null; allRows = null;
        }
        xlsReaderObject = null;

        Console.WriteLine(textOfExcelDocumnet.ToString());
    }

有人可以请一些这个查询的解决方案吗?

1 个答案:

答案 0 :(得分:0)

Cell具有不同的值属性,具体取决于Cell Type。您可以使用类似于以下内容的内容:

switch (cell.CellType)
{ 
    case CellType.Blank:
        return string.Empty;
    case CellType.Boolean:
        return cell.BooleanCellValue;
    case CellType.Formula:
        return cell.CellFormula;
    case CellType.Numeric:
        return cell.NumericCellValue;
    case CellType.String:
        return cell.StringCellValue;
    default:
        return string.Empty;
}