zoukankan      html  css  js  c++  java
  • C#--上文Excel文件数据获取

    Excel文件上传,后台初次认定的只是个有大小的文件流,要想获取上传的数据,则需要用到NPOl

    获取文件流

    1 HttpPostedFileBase filebase=Request.Files[0]; //单独文件访问
    2 Stream inputstream=filebase.InputStream; //获取excel文档流
    3 string filename=filebase.FileName;
    View Code

    Excel文件流转换成datatable

     1    IWorkbook workbook = new XSSFWorkbook(filestream); //.xlsx
     2    ISheet sheet=workbook.GetSheetAt(0); 
     3 
     4     DataTable table = new DataTable();
     5 
     6             IRow headerRow = sheet.GetRow(headerRowIndex);
     7 
     8             if (headerRow == null) return table;
     9 
    10             int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
    11             int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
    12 
    13             //handling header(处理标题).
    14             for (int i = headerRow.FirstCellNum; i < cellCount; i++)
    15             {
    16                 string headColumnName = GetCellValue(headerRow.GetCell(i));  //GetCellValue()根据Excel列类型获取列的值
    17 
    18                 while (table.Columns.Contains(headColumnName)) headColumnName = headColumnName + "+";
    19 
    20                 DataColumn column = new DataColumn(headColumnName);
    21                 table.Columns.Add(column);
    22 
    23             }
    24             for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
    25             {
    26                 IRow row = sheet.GetRow(i);
    27                 DataRow dataRow = table.NewRow();
    28                 if (row != null && row.FirstCellNum > -1)
    29                 {
    30                     for (int j = row.FirstCellNum; j < cellCount; j++)
    31                     {
    32                         if (row.GetCell(j) != null)
    33                         {
    34                             if (dataRow.ItemArray.Length > j)
    35                             {
    36                                 dataRow[j] = GetCellValue(row.GetCell(j));
    37                             }
    38                         }
    39                     }
    40                     table.Rows.Add(dataRow);
    41                 }
    42             }
    43             return table;
    View Code
  • 相关阅读:
    ZOJ 3705 Applications
    UVA 220 Othello
    HDU 2084 数塔
    第五章:变量
    第四章:注释
    第三章:程序结构
    第二章:项目的创建和环境熟悉
    第一章:c#开发环境安装
    处理字段串
    查询表的列信息
  • 原文地址:https://www.cnblogs.com/leap-li/p/7737621.html
Copyright © 2011-2022 走看看